본문 바로가기
Java

2-5 클래스와 객체2 (1) - this

by yukuda 2024. 3. 14.
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());
	}
}