728x90
this 가 하는 일
1️⃣자신의 메모리를 가리킴
2️⃣생성자에서 다른 생성자를 호출
3️⃣자신의 주소를 반환 함
1️⃣자신의 메모리를 가리키는 this
생성된 인스턴스 스스로를 가리키는 예약어
package thisex;
class Birthday{
int day;
int month;
int year;
public void setYear(int year) {
this.year = year;
}
public void printThis() {
sysout(this);
}
}
public class ThisExample {
public static void main(String[] args) {
Birthday b1 = new Birthday();
Birthday b2 = new Birthday();
b1.printThis();
sysout(b2);
b2.printThis();
}
}
public Person(String name, int age){
this.name= name;
this.age = age;
}
note : 위 코드에서 this를 생략하게 되면 name이나 age는 파라미터로 사용되는 name과 age로 인식된다.
2️⃣생성자에서 다른 생성자를 호출 하는 this
public Person() {
this("이름없음",1)
}
public Person(String name, int age){
this.name = name;
this.age = age;
}
note : this를 이용하여 다른 생성자를 호출할 때는 그 이전에 어떠한 statement도 사용할 수 없다. 위와 같이 생성자가 여러 개이고 파라미터만 다른 경우 constructor overloading 이라고 한다.
package thisex;
class Person{
String name;
int age;
public Person() {
this("이름없음", 1); //이걸쓰면 이 생성자 내에 암것도 쓰면 안됨
}
public Person(String name, int age) {
this.name = name;
this.age = age;
}
public Person returnSelf() {
return this; //3️⃣
}
}
public class CallAnotherConst {
public static void main(String[] args) {
Person p1 = new Person();
sysout(p1.name);
sysout(p1.returnSelf());
}
}
'Java' 카테고리의 다른 글
2-7 클래스와 객체2 (3) - static 변수 (1) | 2024.03.18 |
---|---|
2-6 클래스와 객체2 (2) - 객체 간의 협력 ex) 승객과 버스 (0) | 2024.03.18 |
2-4 클래스와 객체1 (4) - 참조 자료형, private (0) | 2024.03.14 |
2-3 클래스와 객체1 (3) - 클래스, 인스턴스, 참조변수, 참조값, 생성자 (0) | 2024.03.14 |
2-2 클래스와 객체1 (2) - 메서드와 함수 (0) | 2024.03.13 |