객체 자신을 가리키는 this
- 인스턴스 자신의 메모리를 가리킴
- 생성자에서 또 다른 생성자를 호출 할 때 사용
- 자신의 주소(참조값)을 반환 함
📌 생성된 인스턴스 메모리의 주소를 가짐
- 클래스 내에서 참조변수가 가지는 주소값과 동일한 주소값을 가지는 키워드
public void setYear(int year) {
this.year = year;
}
📌 생성자에서 다른 생성자를 호출하는 this
- 클래스에 생성자가 여러 개인 경우, this 를 이용하여 생성자에서 다른 생성자를 호출할 수 있음
- 생성자에서 다른 생성자를 호출하는 경우, 인스턴스의 생성이 완전하지 않은 상태이므로 this() statement 이전에 다른 statement를 쓸 수 없음
예제 ) 생성자 2개를 만들어보자
public class Person {
String name;
int age;
// 생성자에서 생성자 호출 가능
public Person() {
this("no name", 1);
}
public Person(String name, int age) {
this.name = name;
this.age = age;
}
public void showPerson() {
System.out.println(name + "," + age);
}
// 테스트 코드
public static void main(String[] arge){
Person person = new Person();
person.showPerson();
}
}
📌 자신의 주소를 반환하는 this
public class Person {
String name;
int age;
// 생성자에서 생성자 호출 가능
public Person() {
this("no name", 1);
}
public Person(String name, int age) {
this.name = name;
this.age = age;
}
public void showPerson() {
System.out.println(name + "," + age);
}
//
public Person getPerson() {
return this;
}
// 테스트 코드
public static void main(String[] arge){
Person person = new Person();
person.showPerson();
System.out.println(preson); // 같은 값 나옴
Person person2 = person.getPerson();
System.out.println(person2); // 같은 값 나옴
}
}
728x90
반응형
'java공부' 카테고리의 다른 글
[객체지향프로그래밍]11_static 변수 (0) | 2022.02.19 |
---|---|
[객체지향프로그래밍]10_객체 간의 협력 (collaboration) (0) | 2022.02.19 |
[객체지향프로그래밍]08_캡슐화(encapsulation) (0) | 2022.02.19 |
[객체지향프로그래밍]07_접근 제어 지시자(access modifier) , 정보은닉(infomation hiding) (0) | 2022.02.19 |
[객체지향프로그래밍]06_참조 자료형 변수 (0) | 2022.02.19 |