자바 상속
- 객체 지향 상속
- 상속 : 자식이 부모 유전자를 물려 받는 것과 유사한 개념
- 선언
- extends 키워드로 선언
- 부모 클래스를 물려받아 확장한다는 의미
- 부모 클래스 -> 슈퍼 클래스(super class)
- 자식 클래스 -> 서브 클래스(sub class)
- extends 키워드로 선언
- 클래스 다중 상속(multiple inheritance) 불허
- C++는 다중 상속 가능
- C++는 다중 상속으로 멤버가 중복 생성되는 문제 있음
- 자바는 인터페이스(interface)의 다중 상속 허용
- C++는 다중 상속 가능
- 모든 자바 클래스는 묵시적으로 Object클래스 상속받음
- java.lang.Object는 클래스는 모든 클래스의 슈퍼 클래스
- 멤버 접근 지정자
- 슈퍼 클래스의 private 멤버 : 서브 클래스에서 접근할 수 없음
- 슈퍼 클래스의 디폴트 멤버 : 서브 클래스가 동일한 패키지에 있을 때, 접근 가능
- 슈퍼 클래스의 public 멤버 : 서브 클래스는 항상 접근 가능
- 슈퍼 클래스의 protected 멤버 : 같은 패키지 내의 모든 클래스 접근 허용, 패키지 여부와 상관없이 서브 클래스는 접근 가능
- 업캐스팅(upcasting)
- 서브 클래스의 레퍼런스를 슈퍼 클래스 레퍼런스에 대입
- 슈퍼 클래스 레퍼런스로 서브 클래스 객체를 가리키게 되는 현상
123456class Person { }class Student extends Person { }Person p;Student s = new Student();p = s; // 업캐스팅
- 다운캐스팅(downcasting)
- 슈퍼 클래스 레퍼런스를 서브 클래스 레퍼런스에 대입
- 업캐스팅된 것을 다시 원래대로 되돌리는 것
- 반드시 명시적 타입 변환 지정
123456class Person { }class Student extends Person { }Person p = new Student("이재문"); // 업캐스팅Student s = (Student)p; // 다운캐스팅, 강제타입변환
- instanceof 연산자
- 레퍼런스가 가리키는 객체의 타입 식별
123456Person p = new Professor();if(p instanceof Person) // trueif(p instanceof Student) // false. Student를 상속받지 않기 때문if(p instanceof Researcher) // trueif(p instanceof Professor) // true
- 레퍼런스가 가리키는 객체의 타입 식별
- 오버라이딩(overriding)으로 다형성 실현
- 하나의 인터페이스(같은 이름)에 서로 다른 구현
- 슈퍼 클래스의 메소드를 서브 클래스에서 각각 목적에 맞게 다르게 구현
1234567891011121314151617181920212223242526272829303132333435363738class Shape { // 도형의 슈퍼 클래스public void draw() {System.out.println("Shape");}}class Line extends Shape {public void draw() { // 메소드 오버라이딩System.out.println("Line");}}class Rect extends Shape {public void draw() { // 메소드 오버라이딩System.out.println("Rect");}}class Circle extends Shape {public void draw() { // 메소드 오버라이딩System.out.println("Circle");}}public class MethodOverridingEx {static void paint(Shape p) { // Shape을 상속받은 객체들이// 매개 변수로 넘어올 수 있음p.draw(); // p가 가리키는 객체에 오버라이딩된 draw() 호출.// 동적바인딩}public static void main(String[] args) {Line line = new Line();paint(line); // Line의 draw() 실행. "Line" 출력paint(new Shape()); // Shape의 draw() 실행. "Shape" 출력paint(new Line()); // 오버라이딩된 메소드 Line의 draw() 실행paint(new Rect()); // 오버라이딩된 메소드 Rect의 draw() 실행paint(new Circle()); // 오버라이딩된 메소드 Circle의 draw() 실행}}