공부/Java

자바 상속 - super, this 예제

진호진호 2024. 2. 8. 15:18

상속

한 클래스가 기존 클래스의 모든 member를 물려받는 것. (생성자는 멤버에 속하지 않음)

- 클래스의 멤버 = 변수, 메소드, 중첩 클래스

 

선언

class 서브클래스 extends 슈퍼클래스

 

-모든 클래스는 오직 하나의 direct superclass를 가짐(단일 상속)

-명시적으로 상속하지 않는 경우 최상위 클래스인 java.lang.Object가 슈퍼클래스

 

class 서브클래스 extends 슈퍼클래스{

-새로운 멤버 추가

-상속한 메소드 재정의

-추상 메소드 구현

-생성자

}

(final class는 상속할 수 없음, final method는 재정의 할 수 없음)

 

슈퍼클래스 멤버 참조

상속한 슈퍼클래스 멤버 접근

public, protected, default - 직접 접근 가능

private - 직접 접근 불가

 

키워드 super 사용

super.슈퍼멤버변수

super.슈퍼멤버메소드

 

super(...) 슈퍼클래스의 생성자 호출

 

예제

 

public class A {
    void foo() { this.bar(); }
    void bar() { System.out.println("a.bar"); }
}

 

case 1 :

class B {
	private A a ; 
	public B(A a) { this.a = a; }
	void foo() { a.foo(); }
	void bar() { System.out.println("b.bar"); }
}
public class java {
    public static void main(String[] args) {
        B b = new B(new A());
        b.foo();
    }
}

case 2 :

class B extends A {
	public B() { }
	void foo() { super.foo(); } 
	void bar() { System.out.println("b.bar"); }
}
public class java {
    public static void main(String[] args) {
        B b = new B();
        b.foo();
    }
}

 

case 1 실행 결과 / a.bar

case 2 실행 결과 / b.bar

 

this는 자신의 객체에 접근할 때 사용된다.

case 2의 경우, 부모 class A의 this는 자식 class B를 가르킨다.