티스토리 뷰

반응형
  • JDK 1.5부터 추가된 개념이다.
  • 부모 클래스의 메소드를 오버라이딩하는 경우, 부모 클래스의 반환 타입은 자식 클래스의 타입으로 변경이 가능하다.
public class Main {
    public static void main(String[] args) {
        Parent parent = new Parent();
        Child child = new Child();
        Parent pc = new Child();

        System.out.println(parent.createNewOne().getClass());
        System.out.println(child.createNewOne().getClass());
        System.out.println(pc.createNewOne().getClass());
    }
}

class Parent {
    protected Parent createNewOne() {
        return new Parent();
    }
}

class Child extends Parent {
    // 부모 클래스로부터 재정의하였으나 반환형을 자식 클래스로 변경할 수 있다.
    @Override public Child createNewOne() {
        return new Child();
    }
}
  • 당연히 인터페이스에도 적용이 가능하다.
public class Main {
    public static void main(String[] args) {
        Testable testable = new TestableImpl();
        System.out.println(testable.tester().getClass());
    }
}

interface Testable {
    Testable tester();
}
class TestableImpl implements Testable {
    @Override public TestableImpl tester() {
        return new TestableImpl();
    }
}
  • 공변 반환 타입이 없는 경우, 자식 클래스를 사용하는 클라이언트 코드에서 명시적 형변환 처리를 해주어야 한다.
  • JDK 1.5 이후의 Java는 공변 반환 타입을 지원하므로, 명시적 형변환을 외부에서 처리할 필요가 없어진다.
댓글
반응형
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2024/05   »
1 2 3 4
5 6 7 8 9 10 11
12 13 14 15 16 17 18
19 20 21 22 23 24 25
26 27 28 29 30 31
글 보관함