Search

this & this( )

this & this( )

this ν‚€μ›Œλ“œ

'this'λŠ” ν˜„μž¬ 객체λ₯Ό κ°€λ¦¬ν‚€λŠ” μ°Έμ‘° λ³€μˆ˜μž…λ‹ˆλ‹€. μ΄λŠ” 객체가 μžμ‹ μ„ μ°Έμ‘°ν•  λ•Œ μ‚¬μš©λ©λ‹ˆλ‹€.

this의 μ£Όμš” μš©λ„

β€’
μΈμŠ€ν„΄μŠ€ λ³€μˆ˜μ™€ λ§€κ°œλ³€μˆ˜ ꡬ뢄
β€’
λ‹€λ₯Έ λ©”μ„œλ“œ 호좜
β€’
ν˜„μž¬ 객체 λ°˜ν™˜
β€’
μΈμŠ€ν„΄μŠ€ λ³€μˆ˜μ™€ λ§€κ°œλ³€μˆ˜ ꡬ뢄: λ©”μ„œλ“œλ‚˜ μƒμ„±μžμ˜ λ§€κ°œλ³€μˆ˜μ™€ μΈμŠ€ν„΄μŠ€ λ³€μˆ˜μ˜ 이름이 같을 λ•Œ κ΅¬λΆ„ν•˜κΈ° μœ„ν•΄ μ‚¬μš©λ©λ‹ˆλ‹€.
public class Person { private String name; // μΈμŠ€ν„΄μŠ€ λ³€μˆ˜ public Person(String name) { // λ§€κ°œλ³€μˆ˜ this.name = name; // thisλ₯Ό μ‚¬μš©ν•˜μ—¬ μΈμŠ€ν„΄μŠ€ λ³€μˆ˜ μ°Έμ‘° } }
Java
볡사
β€’
λ‹€λ₯Έ λ©”μ„œλ“œ 호좜: 같은 클래슀 λ‚΄μ˜ λ‹€λ₯Έ λ©”μ„œλ“œλ₯Ό ν˜ΈμΆœν•  λ•Œ μ‚¬μš©ν•  수 μžˆμŠ΅λ‹ˆλ‹€.
public void method1() { System.out.println("Method 1"); this.method2(); // 같은 클래슀의 λ‹€λ₯Έ λ©”μ„œλ“œ 호좜 } public void method2() { System.out.println("Method 2"); }
Java
볡사
β€’
ν˜„μž¬ 객체 λ°˜ν™˜: λ©”μ„œλ“œμ—μ„œ ν˜„μž¬ 객체λ₯Ό λ°˜ν™˜ν•  λ•Œ μ‚¬μš©ν•©λ‹ˆλ‹€(λ©”μ„œλ“œ 체이닝에 유용).
public Person setName(String name) { this.name = name; return this; // ν˜„μž¬ 객체 λ°˜ν™˜ }
Java
볡사

this() μƒμ„±μž

this()λŠ” 같은 클래슀의 λ‹€λ₯Έ μƒμ„±μžλ₯Ό ν˜ΈμΆœν•˜λŠ” 데 μ‚¬μš©λ˜λŠ” νŠΉλ³„ν•œ κ΅¬λ¬Έμž…λ‹ˆλ‹€.

this()의 νŠΉμ§•

β€’
μƒμ„±μž μ˜€λ²„λ‘œλ”©: μ—¬λŸ¬ μƒμ„±μžκ°€ μžˆμ„ λ•Œ μ½”λ“œ 쀑볡을 μ€„μ΄λŠ” 데 μœ μš©ν•©λ‹ˆλ‹€.
public class Person { private String name; private int age; // κΈ°λ³Έ μƒμ„±μž public Person() { this("Unknown", 0); // λ‹€λ₯Έ μƒμ„±μž 호좜 } // μ΄λ¦„λ§Œ μ§€μ •ν•˜λŠ” μƒμ„±μž public Person(String name) { this(name, 0); // 전체 λ§€κ°œλ³€μˆ˜ μƒμ„±μž 호좜 } // λͺ¨λ“  ν•„λ“œλ₯Ό μ΄ˆκΈ°ν™”ν•˜λŠ” μƒμ„±μž public Person(String name, int age) { this.name = name; this.age = age; } }
Java
볡사
β€’
μ€‘μš”ν•œ κ·œμΉ™: this()λŠ” μƒμ„±μžμ˜ 첫 번째 λ¬Έμž₯으둜만 μ‚¬μš©ν•  수 μžˆμŠ΅λ‹ˆλ‹€.
β€’
μˆœν™˜ 호좜 κΈˆμ§€: μƒμ„±μž κ°„μ˜ μˆœν™˜ ν˜ΈμΆœμ€ 컴파일 였λ₯˜λ₯Ό λ°œμƒμ‹œν‚΅λ‹ˆλ‹€.

this와 this()의 차이점

λ‹€μŒμ€ this와 this()의 μ£Όμš” μ°¨μ΄μ μž…λ‹ˆλ‹€:
ꡬ뢄
this
this()
μ •μ˜
ν˜„μž¬ 객체λ₯Ό μ°Έμ‘°ν•˜λŠ” λ³€μˆ˜
같은 클래슀의 λ‹€λ₯Έ μƒμ„±μžλ₯Ό ν˜ΈμΆœν•˜λŠ” λ©”μ„œλ“œ
μ‚¬μš© μœ„μΉ˜
클래슀 λ‚΄ μ–΄λ””μ„œλ“  μ‚¬μš© κ°€λŠ₯
μƒμ„±μžμ˜ 첫 번째 λ¬Έμž₯으둜만 μ‚¬μš© κ°€λŠ₯
μ£Όμš” μš©λ„
μΈμŠ€ν„΄μŠ€ λ³€μˆ˜ μ°Έμ‘°, ν˜„μž¬ 객체 λ°˜ν™˜
μƒμ„±μž μ½”λ“œ 쀑볡 제거, μ΄ˆκΈ°ν™” μœ„μž„
문법
객체 참쑰 (예: this.name)
λ©”μ„œλ“œ 호좜 (예: this() λ˜λŠ” this(param))