TIL | JAVA 참조변수 super / 생성자 super

김윤희·2022년 8월 1일
0

참조변수 super와 생성자 super

참조변수 super


  • 객체 자신을 가리키는 참조변수. 인스턴스 메서드(생성자)내에만 존재(static 메서드 내에서 사용불가)
  • 조상의 멤버를 자신의 멤버와 구별할 때 사용

📝 예제 1 )

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

class Parent {intx = 10; /*super.x*/}

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

결과
x=20
this.x=20
super.x=10

📝 예제 2 )

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

class Parent {intx = 10; /*super.x와 this.x 둘 다 가능*/}

class Child extends Parent{
    void method(){
    	System.out.println("x="+x);
        System.out.println("this.x"+this.x);
        System.out.println("super.x"+super.x);
    }
}

결과
x=10
this.x=10
super.x=10



super() - 조상의 생성자


  • 조상의 생성자를 호출할 때 사용
  • 조상의 멤버는 조상의 생성자를 호출해서 초기화
class Point {
	int x, y;
    
    Point(int x, int y){
    	this.x = x;
        this.y = y;
    }
}

class Point3D extends Point{
	int z;
    
    Point3D(int x, int y, int z){
    	this.x = x;		//조상의 멤버를 초기화
        this.y = y;		//조상의 멤버를 초기화
        this.z = z;
    }
}

❗ 위와 같이 자손의 생성자에서는 자손이 선언한 것만 초기화를 시켜야하고, 조상의 멤버를 초기화하면 안된다!
아래와 같이 수정해서 작성해야한다😑❗

    Point3D(int x, int y, int z){
    	super(x, y);	//조상클래스의 생성자 Point(int x, int y)를 호출
        this.z = z;		//자신의 멤버를 초기화
    }

📌 생성자의 첫 줄에 반드시 생성자를 호출해야한다 !
그렇지 않으면 컴파일러가 생성자의 첫 줄에 super();를 삽입

   class Point{
   	int x;
    int y;
    
    point () {
    	this(0,0);
    ]
    
    point(int x, int y) {
    	this.x = x; //생성자의 첫 줄에 생성자를 호출하지 않음
        this.y = y;
    }
   }

✔ 위에 코드처럼 첫 줄에 생성자를 호출하지 않았을 경우 컴파일러가 자동으로 삽입해 준다

   class Point{
   	int x;
    int y;
    
    point () {
    	this(0,0);
    ]
    
    point(int x, int y) {
    	super();	//Object();
    	this.x = x;
        this.y = y;
    }
   }

0개의 댓글