/ JAVAJUNGSUK

Ch7-10~11. super

자바의 정석 기초편

0. 목차



Chapter7. 객체지향 프로그래밍Ⅱ

Ch7 - 10. 참조변수 super

Ch7 - 11. super() - 조상의 생성자



Ch7 - 10. 참조변수 super


▶ 참조변수 super란?

▷ super ≒ this
▷ this : lv와 iv 구별
▷ super : 조상 멤버와 자신 멤버 구별
▷ 객체 자신을 가리키는 참조변수
▷ 인스턴스 메서드(생성자) 내에서만 존재
▷ static 메서드 내에서는 사용 불가


▶ 실습

▷ 부모와 자식 모두 x를 가진 경우
class Act {

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

class Parent {

	int x = 10;
}

class Child extends Parent {

	int x = 20;
	
	void method() {
		
		System.out.println("x = " + x); // 가까운 쪽의 x, 바로 위의 int x = 20;
		System.out.println("this.x = " + this.x);
		System.out.println("super.x = " + super.x);
	}
}

// console
x = 20
this.x = 20
super.x = 10


▷ 부모만 x를 가진 경우
class Act {
	
	public static void main(String[] args) {
		
		Child c = new Child();
		c.method();
	}
}

class Parent {

	int x = 10;
}

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

// console
x = 10
this.x = 10
super.x = 10




Ch7 - 11. super() - 조상의 생성자


▶ 조상의 생성자 super()란?

▷ 참조변수 super ≠ 조상의 생성자 super()
▷ 조상의 생성자 super()는 생성자this와 같음
▷ 조상의 생성자를 호출할 때 사용
▷ 생성자와 초기와 블럭은 상속 불가
▷ 조상의 멤버는 조상의 생성자를 호출해서 초기화


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


▶ 실습

▷ 왜 에러가 났을까?
class Point {
	int x;
	int y;
	
	Point(int x, int y) {
		this.x = x;
		this.y = y;
	}
	
	String getLocation() {
		return "x : " + x + "y : " + y;
	}
}

class Point3D extends Point {
	int z;
	
	Point3D(int x, int y, int z) {
		this.x = x;
		this.y = y;
		this.z = z;
	}
	
	String getLocation() {
		return "x : " + x + "y : " + y + "z : " + z;
	}
}

class PointTest {
	public static void main(String[] args) {
		Point3D point3d = new Point3D(1, 2, 3);
	}
}

// console
Exception in thread "main" java.lang.Error: Unresolved compilation problem: 
Implicit super constructor Point() is undefined. Must explicitly invoke another constructor

at baek_ch02.Point3D.<init>(Point.java:20)
at baek_ch02.PointTest.main(Point.java:33)
▷ 기본 생성자 Point() {}의 부재 때문


▷ 에러 수정