슈퍼 클래스의 private 멤버
- 슈퍼 클래스의 private 멤버는 다른 모든 클래스에 접근 불허
- 클래스내 멤버들에게만 접근 허용
슈퍼 클래스의 디폴트 멤버
- 슈퍼 클래스의 디폴트 멤버는 패키지내 모든 클래스에 접근 허용
슈퍼 클래스의 public 멤버
- 슈퍼 클래스의 public 멤버는 다른 모든 클래스에 접근 허용
슈퍼 클래스의 protected 멤버
- 같은 패키지 내의 모든 클래스 접근 허용
- 다른 패키지에 있어도 서브 클래스는 슈퍼 클래스의 protected 멤버 저근 가능
상속 관계에서의 생성자
서브 클래스 생성자 작성 원칙
서브 클래스에서 슈퍼 클래스의 생성자를 선택하지 않는 경우
서브 클래스의 생성자가 슈퍼 클래스의 생성자를 선택하지 않은 경우
class A { public A() { System.out.println("A"); } }class B extends A { public B() { System.out.println("B"); } }public class ConstructorEx2 { public static void main(String[] args) { B b = new B(); } }
컴파일러는 서브 클래스의 기본 생성자에 대해 자동으로 슈퍼 클래스의 기본 생성자와 짝을 맺는다. 따라서 실행 결과가 A,B가 나왔다.
서브 클래스에서 슈퍼 클래스의 생성자를 선택하는 방법
package Inheritance; class A4 { public A4() { System.out.println("A"); } public A4(int x) { System.out.println("매겨변수생성자A" + x); } }class B4 extends A4 { public B4() { System.out.println("B"); } public B4(int x) { //이때 x는 5 super (x); System.out.println("매개변수생성자B" + x); } }public class ConstructorEx4 { public static void main(String[] args) { B4 b = new B4 (5); } }
class Person { String name, id; public Person(String name) { this.name = name; } }class Student extends Person { String grade,department; public Student(String name) { super(name); } }public class UpcastingEx { public static void main(String[] args) { Person p; Student s = new Student("민팔"); p = s; // 업캐스팅 System.out.println(p.name); // 오류 없음 // p.grade = "A"; // 컴파일 오류 // p.department = "Com"; // 컴파일 오류 } }
public class DowncastingEx { // Person과 Student는 위와 동일 public static void main(String[] args) { Person p = new Student("민팔"); // 업캐스팅 Student s; s = (Student)p; // 다운캐스팅 System.out.println(s.name); // 오류 없음 s.grade = "A"; // 오류 없음 } }