개발자 데뷔!

08. [Java] this 예약어 본문

프로그래밍 언어/Java

08. [Java] this 예약어

물꼮이 2022. 1. 31. 21:49

 

this
: 생성된 인스턴스 스스로를 가리키는 예약어

this는 크게 다음 세가지 역할로 쓰임을나눌 수 있다.

1. 자신의 메모리를 가리키는 this
2. 생성자에서 다른 생성자를 호출하는 this
3. 자신의 주소를 반환하는 this

보통 1번의 경우로 가장 많이 쓰이지만, 

 예제와 함께 알아두자.

 

1. 자신의 메모리를 가리키는 this

클래스 코드에서 사용하는 this는, 생성된 인스턴스 자신을 가리킨다. 

 

ex)

package thisex;

class BirthDay{

	int day;
	int month;
	int year;
	
	public void setYear(int year) {
		this.year = year;		// bDay.year = year 와 동치
	}
	
	public void printThis() {
		System.out.println(this);  // this = bDay 즉, 클래스 전체를 출력
	}
}

public class ThisExmaple {

	public static void main(String[] args) {
		
		BirthDay bDay = new BirthDay();	// this가 가리킬 인스턴스가 이부분에서 정해짐
		bDay.setYear(2000);
		System.out.println(bDay);
		bDay.printThis();
	}
}

 

 

2. 생성자에서 다른 생성자를 호출하는 this

ex)

package thisex;

class Person{
	String name;
	int age;
	
	// 생성자1
	Person(){
		this("이름없음", 1);  // this를 사용해 Person(String, int)형태인 생성자2 호출
	}
	// 생성자2
	Person(String name, int age){		// 실제 호출되는 생성자2
		this.name = name;
		this.age = age;
	}
	
}

public class CallAnotherConst {

	public static void main(String[] args) {

		Person noName = new Person();		// 기본생성자인 생성자1이 먼저 생성되지만, this로 인해
		System.out.println(noName.name);	// 다시 생성자2를 호출하게됨
		System.out.println(noName.age);

	}
}

 

3. 자신의 주소를 반환하는 this

ex) 

package thisex;

class Person{
	String name;
	int age;
	
    //생성자1
	Person(){
		this("이름없음", 1);  // 생성자2를 호출
	}
	
    //생성자2
	Person(String name, int age){
		this.name = name;
		this.age = age;
	}
	
    // class형을 반환
	Person returnItSelf() {
		return this;
	}
}

public class CallAnotherConst {

	public static void main(String[] args) {

		Person noName = new Person();
		System.out.println(noName.name);
		System.out.println(noName.age);
		
		Person p = noName.returnItSelf();		// this 값을 클래스 변수에 대입
		System.out.println(p);
		System.out.println(noName);
	}
}