Java
[Java] this에 대하여
개발자 윤정
2021. 6. 10. 10:02
01. this의 역할
- 자신의 메모리를 가리킵니다.
- 생성자에서 다른 생성자를 호출합니다.
- 인스턴스 자신의 주소를 반환합니다.
01-01. 자기 자신을 메모리를 가리키는 this
01-02. 생성자에서 다른 생성자를 호출하는 this
public Person() {
this("이름 없음", 1); // public Person(String name, int age) 생성자를 호출
}
public Person(String name, int age) {
this.name = name;
this.age = age;
}
※ 생성자에서 this로 다른 생성자를 호출할 경우 호출하는 statement가 항상 첫번째 줄이여야 합니다.
01-03. 인스턴스 자신의 주소를 반환하는 this
// class Person
package thisex;
public class Person {
public Person getSelf() {
return this;
}
}
// class PersonController
package thisex;
public class PersonController {
public static void main(String[] args) {
Person personLee = new Person();
System.out.println(personLee);
Person p = personLee.getSelf();
System.out.println(p);
}
}