상속

Moon·2024년 2월 23일

Java

목록 보기
13/45
  • 자식클래스는 하나의 부모클래스에서만 상속받을 수 있다.
  • 부모클래스로부터 상속받을 수 있는 요소는 변수메소드다.

    생성자는 상속받을 수 없다.

접근 제어자

protected

같은 패키지, 다른 패키지에서 상속 가능

package com.codelatte.inheritance.dog;

public class GrandParentDog {
    String leg = "long";
    void bite() {
        System.out.println("으르릉! 깨물다");
    }
}
package com.codelatte.inheritance.dog;

public class ParentDog extends GrandParentDog {
    protected String color = "black";
    protected void bark() {
        System.out.println("왈왈!");
    }
}

default

같은 패키지안에서만 상속 가능

package com.codelatte.inheritance.outdog;
import com.codelatte.inheritance.dog.ParentDog;

public class ChildDog extends ParentDog {
    public void info() {
        System.out.println(leg); // 접근 불가능
        System.out.println(color);
    }

    public void howling() {
        bite(); // 호출 불가능
        bark();
        System.out.println("아오오오~~");
    }
}

생성자

super()

부모의 생성자가 명시적으로 선언된 경우, 자식 클래스에서 부모의 생성자 중 하나를 반드시 호출해야 함.

public class ParentDog {
    String name;

    ParentDog(String name) {
        this.name = name;
    }

    ParentDog(String name1, String name2) {

    }
}
public class ChildDog extends ParentDog {
    ChildDog(String name) {
        super(name); // 부모 클래스의 ParentDog(String name)생성자 호출
    }
}

super()를 명시적으로 호출하지 않아도 되는 예외

  1. 부모 클래스의 생성자가 명시적으로 선언되지 않은 경우
  2. 부모 클래스에 기본 생성자만 있을 경우
public class ParentDog {
    String name;

    ParentDog() {
        this.name = "이쁜 강아지"
    }

}
public class ChildDog extends ParentDog {
    ChildDog(String name) {
        // super(); 생략 가능
   }

    ChildDog(String name1, String name2) {
       // super(); 생략 가능
   }
}

0개의 댓글