참조 변수 super

‍김다솔·2021년 4월 13일

참조 변수 super

public class c7_3_210413 {
	public static void main(String[] args) {

		Child c = new Child();
		c.method();
	}

}

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

class Child extends Parent {
	int x = 20; // this.x

	void method() {
		System.out.println("x:" + x); // 20
		System.out.println("this.x:" + this.x); // 20
		System.out.println("super.x:" + super.x); // 10
	}
}
class Parent2 {
	int x = 10; // super.x, this.x 둘 다 가능
}

class Child2 extends Parent2 {
	void method() {
		System.out.println("x:" + x);
		System.out.println("this.x:" + this.x);
		System.out.println("super.x:" + super.x);
	}
}

this : lv와 iv 구별
super : 조상 멤버와 자식 멤버 구별

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

super()

class Point {
	int x, y;

	Point(int a, int b) {
		this.x = a;
		this.y = b;
	}
}

class Point3D extends Point {
	int z;

	public Point3D(int a, int b, int c) {
		// 에러는 아니지만 비추천
		// this.x=a;
		// this.y=b;

		super(a, b); // 조상 클래스의 생성자 Point(int a, int b) 호출
		this.z = c;
	}
}
  • 자손 클래스에서 조상 클래스의 생성자 호출할 때 사용
  • 조상의 멤버는 조상의 생성자를 호출해서 초기화

class Point2 { // extends Object
	int x, y;

	Point2() {
		this(0, 0); // 첫 줄에 반드시 생성자 호출
	}

	Point2(int x,int y){
		super(); // Object(); // 첫 줄에 반드시 생성자 호출, 그렇지 않으면 컴파일러가 첫 줄에 super(); 삽입
		this.x=x;
		this.y=y;
	}
}

class Point3D2 extends Point2 {
	int z;
    
    Point3D2(int x, int y, int z) {
    	// super(); 는 Point2()를 호출하므로
        // Point2 자식 클래스에서 기본 생성자를 정의하지 않으면 에러 발생
        // 또는
        super(x,y); // 조상의 생성자 Point2(int x, int y) 호출
    	// this.x = x;
        // this.y = y;
        this.z = z;
    }
}

생성자의 첫 줄에 반드시 다른 생성자를 호출해야 한다.

profile
💻🎧⚽

0개의 댓글