두 개의 인터페이스 A, B (다른 구성 요소에 있음)가 있습니다. 둘 다 동일한 서명 (MyMethod
)을 가진 메소드를 선언합니다. 두 인터페이스는 세 번째 인터페이스 (C)에 상속됩니다.new-keyword를 사용하여 두 인터페이스의 메소드를 결합하십시오.
첫 번째 두 인터페이스 (A, B)에서 선언 된 메서드는 항상 동일한 값 (A와 B)을 반환하기위한 것이므로 C에서 파생 될 때 인터페이스를 명시 적으로 구현하고 싶지 않습니다.
new 키워드를 사용하면서 세 번째 인터페이스에서도이 메서드를 선언하면이 작업을 수행 할 수 있습니다.
public interface A {
MyType MyMethod();
}
public interface B {
MyType MyMethod();
}
public interface C : A,B{
new MyType MyMethod();
}
public class ImplementingClass : C{
public MyType MyMethod(){
// do somethin
// return something
}
}
예상치 못한 문제가 있습니까? 아니면이 나쁜 스타일입니까?
업데이트
죄송합니다. 초기 질문에 전체 내용이 표시되지 않았습니다. 문제는 C의 인터페이스 참조에서 MyMethod를 호출하려고 할 때 발생합니다. 컴파일러는 컴파일하지 않습니다.
C aReferenceToC=new CImplementingClass();
aReferenceToC.MyMethod(); // <<< Here the compiler will throw an exception
전체 예를
C myCImplementationAsAnInterfaceReference = new MyCImplementation();
myCImplementationAsAnInterfaceReference.MyMethod(); // This does not compile without declaring MyMethod in C with the new-Keyword
MyCImplementation myCImplementationReference= new MyCImplementation();
myCImplementationReference.MyMethod(); // This however will always compile and run
public interface A {
int MyMethod();
}
public interface B {
int MyMethod();
}
public interface C : A, B {
}
public class MyCImplementation : C {
public int MyMethod() {
return 1;
}
}
-1 이것은 programmers.stackexchange (농담)에 속해 있습니다. 좋은 질문입니다. –
방금 시도한이 클래스를 구현하는 클래스는 하나의 메서드 만 구현하므로 호출되는 메서드는 무작위로 나타납니다. –
@HCL 전체 예제를 사용하면 정확합니다. 새 MyType MyMethod()를 연결하지 않으면 C 유형을 사용할 수 없습니다. 인터페이스 C에서 두 개의 기본 인터페이스가 동일한 메소드 서명을 갖는 이유에 대해 궁금합니다. –