[Java] Java의 정석 정리 (this)

송병훈·2022년 9월 24일
0

자바의 정석

목록 보기
3/15


참조변수 this

코드를 먼저 볼게요.

class Car {
	String color;		// 색상
	String gearType;    // 변속기 종류 - auto(자동), manual(수동)
	int door;			// 문의 개수

	Car() {
		this("white", "auto", 4);	// 여기 this가 쓰였어요.
	}

	Car(Car c) {	// 인스턴스의 복사를 위한 생성자.
		color    = c.color;
		gearType = c.gearType;
		door     = c.door;
	}

	Car(String color, String gearType, int door) {
		this.color    = color;		// 여기도 this가 쓰였어요.
		this.gearType = gearType;
		this.door     = door;
	}
}
class CarTest3 {
	public static void main(String[] args) {
		Car c1 = new Car();
		Car c2 = new Car(c1);	// c1의 복사본 c2를 생성한다.
		System.out.println("c1의 color=" + c1.color + ", gearType=" + c1.gearType+ ", door="+c1.door);
		System.out.println("c2의 color=" + c2.color + ", gearType=" + c2.gearType+ ", door="+c2.door);

		c1.door=100;	// c1의 인스턴스변수 door의 값을 변경한다.
		System.out.println("c1.door=100; 수행 후");
		System.out.println("c1의 color=" + c1.color + ", gearType=" + c1.gearType+ ", door="+c1.door);
		System.out.println("c2의 color=" + c2.color + ", gearType=" + c2.gearType+ ", door="+c2.door);
	}
}

자 이 중에서 두 개만 볼게요.


/** this가 생성자로 쓰인 경우 **/
Car() {
		this("white", "auto", 4);	// 여기 this가 쓰였어요.
        //Car("white", "auto", 4); 와 동일하다
}


/** 변수에 this가 쓰인 경우 **/
Car(String color, String gearType, int door) {
    this.color    = color;		// 여기도 this가 쓰였어요.
    this.gearType = gearType;
    this.door     = door;
}
  1. this가 생성자로 쓰인 경우
    { } 안에 this("white", "auto", 4); 는 Car클래스 안에 있는
    Car("white", "auto", 4); 생성자를 호출하는 것과 같아요.
    "같은 클래스의 생성자" 임을 직관적으로 보여주죠.

  2. 변수에 this가 쓰인 경우
    Car(String color, String gearType, int door) {} 생성자를 보면,
    좌변에는 this.color, 우변에는 color가 있죠?

    좌변의 color는 "Car 클래스의 멤버로 선언된 인스턴스 변수(전역변수)"
    우변의 color는 매개변수로 들어온 지역변수에요.

    매개변수로 받은 지역변수 color를, 멤버변수(지역변수) color에 저장시키면서
    인스턴스를 생성하는 코드죠.

간단하게 말해서 this는 의미 그대로

변수에 쓰이면 "이 클래스의 전역변수"
생성자에 쓰이면 "이 클래스의 생성자"
라는 의미로 쓰입니다!!

profile
성실하고 꼼꼼하게

0개의 댓글