자바의 정석 7장 (15일차) - 참조변수(super & this)

728x90

참조변수(super)

IV, LV 구별에 사용되는 this 와는 다르게 super는 조상멤버와 자신의 멤버를 구별할 때 사용

  • super는 parent의 x로 구별하여 사용하고 this는 child의 x로 구별하여 사용함
  • 일반 x는 child의 멤버변수로 오버라이딩되어 20으로 출력됨

조상의 변수가 존재하지만 자식의 변수가 존재하지 않을 때는 this를 사용해도 조상의 변수로 사용됨 ( = 10으로 통일)

 

출력문: 

x = 20
super.x = 10
this.x = 20

	public static void main(String[] args) {
		child c = new child();
		c.method();
	}
}

class parents{
	int x = 10;
}

class child extends parents{
	int x = 20;
	void method() {
		System.out.println("x = " + x);
		System.out.println("super.x = " + super.x);
		System.out.println("this.x = " + this.x);
	}
}

 

super()는 조상의 생성자를 불러올 때 사용됨

  • parent 클래스에서 생성자로 this.를 사용해 x, y를 초기화 시킴
  • 아래 상속받은 child 클래스에서 super()를 사용하여 x,y값을 불러온 후 초기화시킴
  • 본인의 멤버변수 z는 위와 동일하게 this.를 사용하여 초기화

생성자의 조건

반드시 생성자의 첫줄에 생성자를 호출해야 함

class parents{
	int x;
	int y;
	public parents(int x, int y) {
		this.x = x;
		this.y = y;
	}
}
class child extends parents{
	int z;
	
	public child(int x, int y, int z) {
		super(x, y);
		this.z = z;
	}
}
728x90