정의
- 자손 클래스에서 조상 클래스로부터 상속받은 멤버를 가리킬 때 사용하는 참조변수
쓰일 때
상속받은 맴버와 자신의 멤버의 이름이 같을 때 super를 붙여서 구별한다.
예시
class Main{ public static void main(String[] args) { Point3D p3 = new Point3D(); p3.show_super(); } } class Point{ int x= 0 , y = 1; } class Point3D extends Point { int x = 3; void show_super(){ System.out.printf("x : %d, this.x : %d, super.x : %d",x,this.x,super.x); } } // 출력 : x : 3, this.x : 3, super.x : 0super()
- 조상의 생성자를 호출
예시
class Main{ public static void main(String[] args) { Point3D p3 = new Point3D(1,2,3); p3.show_super(); } } class Point{ int x, y; Point(int x, int y){ this.x = x; this.y = y; } } class Point3D extends Point{ int z = 0; Point3D(int x, int y, int z){ super(x,y); this.z = z; } void show_super(){ System.out.printf("x : %d, super.y : %d, this.z : %d",x, super.y, this.z); } } // 출력 : x : 1, super.y : 2, this.z : 3
- 클래스 자신에 선언된 변수는 자신의 생성자가 초기화를 하도록 작성하는 것이 좋다