JAVA/java 공부

[JAVA] class 클래스와 객체 : this 예약어

congs 2023. 3. 25. 21:35

this 예약어

생성된 인스턴스 자신을 가리키는 예약어

(클래스 코드에서 사용하는 this = 생성된 인스턴스 자신을 가리키는 역할)

 

다른 생성자 호출 this

class Day{
	int day;
	int month;
	int year;
	
	Day(int Day, int month, int year){
		this.day = day;
		this.month = month;
		this.year = year;
	}

	Day(){
		//this.day=4; //단, 호출하는 다른 생성자 이전에 코드를 넣지x
		this(6,3,2023); 
		//this를 이용하여 다른 생성자 호출:	Day(int Day, int month, int year)호출
	}	
}

 

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

public void print() {
	System.out.println(this); // .print() => doIt.Day@메모리주소 출력
}

 

자신의 주소를 반환하는 this

Day returnItSelf() {
	return this; //this반환
	//반환형은 class명 

public static void main(String[] args){
	Day d = new Day();
	Day d2 = Day.returnItSelf();
	System.out.println(d2);
	System.out.println(Day);
	// 결과: doIt.Day@메모리주소(주소값) 출력
	
//class내에서 this 사용시 = 자신의 주소값을 반환!