생성자 - this

로로·2023년 8월 7일

  • 참조 변수 출력시 heap에 있는 주소 출력

  • b1, b2는 각각 다른 주소값을 가짐
  • b1의 this와 b2의 this가 가르키는 것은 각각 다름

1️⃣ 자신의 메모리를 가리킴
2️⃣ 생성자에서 다른 생성자를 호출
3️⃣ 자신의 주소를 반환


1️⃣ 자신의 메모리를 가르키는 this

public class BirthDay(){
	int day;
    int month;
    int year;
    
    public void setYear(int year){
    	this.year = year;
    }
    
}

2️⃣ 생성자에서 다른 생성자 호출

public class BirthDay(){
	int day;
    int month;
    int year;


    public BirthDay(int day, int month, int year){
    	this.day = day;
        this.month = month;
        this.year = year;
    }

    public BirthDay(){
    	// int day = 0 ;
        // this 사용할 때는 앞에 어떤 구문도 오면 안됨.
        // 1. 아래 this ~~ 구문이 실행된 후에야 생성이 완료 되기 때문
        // 2. 생성되지 않은 메모리에 값을 할당하게 되는 오류가 발생할 수 있기때문
    	this(7, 8, 2023); // 생성자에서 다른 생성자 호출
    }
}

3️⃣ 자신의 주소 반환

public class BirthDay(){
	int day;
    int month;
    int year;
    
    public BirthDay returnSelf(){
    	return this;
    }
    
    public void printThis(){
    	System.out.println(this);
    }
    
    public void static main(String[] args){
    	BirthDay day1 = new BirthDay();
    	BirthDay day2 = new BirthDay();
        
        System.out.println(day1);
        System.out.println(day2);
        
        // 결과
        // chapter2.BirthDay@75b84c92
		// chapter2.BirthDay@6bc7c054
        
        day1.printThis();
        day2.printThis();
        
        // 결과
        // chapter2.BirthDay@75b84c92
		// chapter2.BirthDay@6bc7c054
    }
    
}
profile
청로하~🏝️

0개의 댓글