본문 바로가기

공부 자료/자바[JAVA]

[Java] super & super()

[super]

: 자손 클래스에서 조상 클래스로부터 상속받은 멤버를 참조하는데 사용되는 참조변수

>> 즉, 조상 클래스에 존재하는 멤버를 가져와서 사용하는 경우를 의미

(멤버변수와 지역변수의 이름이 같을 때 this를 붙여서 구별했듯 상속받은 멤버와 자신의 멤버의 이름이 동일할 경우 super을 붙여서 구분함)

 

class Ex{
	public static void main(String args[]){
    	Child c = new Child();
        c.method(); //Child 클래스를 참조하여 Child 클래스 내 method() 메서드를 사용
     }
}

class Parent {int x = 10;} //super.x

class Child extends Parent { // Child 클래스가 Parent 클래스를 상속받음
	int x = 20; //this.x
    
    void method() {
    	System.out.println("x=" + x); //Child 내의 x값
        System.out.println("this.x="+this.x); // Child 내의 x값
        System.out.println("super.x"+super.x); //상위 클래스의 x를 참조하기에 Parent의 x값
    }
}

 

[super()]

: 조상의 생성자를 호출하는 생성자

: 클래스 자신에 선언된 변수는 자신의 생성자가 초기화를 책임지도록 작성하는 것이 좋기 때문에 상속받은 변수를 초기화 할 경우 super()을 사용함

 

public class Ex{
	public static void main(String[] args){
    	Point3D p = new Point3D();
        System.out.println("x=" + p.x + ",y=" + p.y + ",z=" + p.z);
    }
}

class Point {
	int x, y;
    
    Point(int x, int y){ //Point 클래스의 생성자
    	this.x = x;
        this.y = y;
    }
}

class Point3D extends Point{
	int z;
    
    Point3D(int x, int y, int z){
    	super(x,y); //부모 클래스 내의 변수이기 때문에 부모 클래스 내 생성자를 호출함
        //즉 Point(int x, int y)를 호출함
        this.z = z;
    }
}