JAVA

객체지향 생성자 this(), 참조변수 this

연93 2022. 9. 25. 16:30
  • 생성자에서 다른 생성자 호출할 때 사용
  • 다른 생성자 호출시 첫 줄에서만 사용가능
  • 클래스 이름대신 this()를 사용한다.
class Car2 {
	String color;
	String gearType;
	int door;
	
	Car2(){
		this("white", "auto", 4);
	}
	
	Car2(String color){
		this(color, "auto", 4);
	}
	
	Car2(String color, String gearType, int door){
		this.color = color;
		this.gearType = gearType;
		this.door = door;
	}
}

코드의 중복을 막기위해 같은 클래스 내에 코드는 this로 호출한다

 

**참조변수 this**

  • 인스턴스 자신을 가르키는 참조변수
  • 인스턴스 메서드 (생성자 포함)에서 사용가능
  • 지역변수 lv 와 인스턴스 변수 iv를 구별할 때 사용
Car(String c, String g, int d){
		// color는 iv, c는 lv
		color = c; 
		gearType = g;
		door = d;
	}
Car(String color, String gearType, int door){
// this.color는 iv, color는 lv

this.color = color;
this.gearType = gearType;
this.door = door;
}

------------------------------------------------------------------------------------------------------------------------------------------------

static long add(long a, long b){ // 클래스 메서드 (static메서드)
	return a + b; // static은 iv사용불가 this = 객체 자신이므로 this 사용불가