유형이 두 개의 인터페이스를 구현하고 각각 interface동일한 서명을 가진 메소드를 정의하는 경우 실제로는 하나의 메소드 만 있으며 구별 할 수 없습니다. 예를 들어 두 메소드가 리턴 유형이 충돌하면 컴파일 오류가됩니다. 이것은 상속, 메소드 재정의, 숨기기 및 선언의 일반적인 규칙이며, 상속 된 두 interface메소드뿐만 아니라 interface슈퍼 class메소드 사이의 가능한 충돌에도 적용 되거나 제네릭의 유형 삭제로 인한 충돌에도 적용됩니다.
호환성 예
여기에 (선물을 제시하는 것과 같은) 방법 interface Gift이있는 present()및가 있는 예가 interface Guest있습니다.present() (, 게스트가없는 현재와하지에로) 방법을.
Presentable johnnya Gift와 a Guest입니다.
public class InterfaceTest {
interface Gift { void present(); }
interface Guest { void present(); }
interface Presentable extends Gift, Guest { }
public static void main(String[] args) {
Presentable johnny = new Presentable() {
@Override public void present() {
System.out.println("Heeeereee's Johnny!!!");
}
};
johnny.present(); // "Heeeereee's Johnny!!!"
((Gift) johnny).present(); // "Heeeereee's Johnny!!!"
((Guest) johnny).present(); // "Heeeereee's Johnny!!!"
Gift johnnyAsGift = (Gift) johnny;
johnnyAsGift.present(); // "Heeeereee's Johnny!!!"
Guest johnnyAsGuest = (Guest) johnny;
johnnyAsGuest.present(); // "Heeeereee's Johnny!!!"
}
}
위의 스 니펫은 컴파일되고 실행됩니다.
참고 하나가 @Override 필요합니다! . 이 때문입니다 Gift.present()및 Guest.present()"이다 @Override(-equivalent" JLS 8.4.2 ).
따라서의 johnny 구현 은 하나만 있으며 a로 또는 a 로 present()처리하는 방법은 중요하지 않습니다 . 호출 할 메소드는 하나뿐입니다.johnnyGiftGuest
비 호환성 예
다음은 상속 된 두 메소드가 동일하지 않은 예입니다 @Override.
public class InterfaceTest {
interface Gift { void present(); }
interface Guest { boolean present(); }
interface Presentable extends Gift, Guest { } // DOES NOT COMPILE!!!
// "types InterfaceTest.Guest and InterfaceTest.Gift are incompatible;
// both define present(), but with unrelated return types"
}
이것은 또한 멤버로부터 상속받는 멤버 interface가 멤버 선언의 일반적인 규칙을 준수해야 함을 반복합니다 . 여기에서 우리는이 Gift와 Guest정의 present()호환되지 않는 반환 형식으로 하나 void다른 boolean. 같은 이유로 당신은 할 수 없다는 void present()하고 boolean present()한 가지 유형에서, 컴파일 오류이 예의 결과.
요약
@Override메서드 재정의 및 숨기기의 일반적인 요구 사항에 따라 동등한 메서드를 상속 할 수 있습니다 . 그들은 이후 내용입니다 @Override -equivalent 효과적으로 구현하는 하나의 방법이있다, 따라서 선택 / 구별 할 것도 없다.
컴파일러는 일단 어떤 인터페이스가 어떤 인터페이스인지 결정하지 않아도됩니다. @Override 동일한 되면 동일한 메소드 입니다.
잠재적 인 비 호환성을 해결하는 것은 까다로운 작업 일 수 있지만 이는 또 다른 문제입니다.
참고 문헌