Dev./java
[Java] 공변 반환 타입(covariant return type)
인쥭
2022. 2. 28. 03:11
반응형
- 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는 공변 반환 타입을 지원하므로, 명시적 형변환을 외부에서 처리할 필요가 없어진다.