Java不支持多继承,但我们可以使用接口实现多继承的效果。在接口中,一个类可以实现多个不能通过extends关键字实现的接口。 请参考 java中的多重继承 更多信息。 假设我们有两个具有相同方法名(geek)和不同返回类型(int和String)的接口
null
public interface InterfaceX { public int geek(); } public interface InterfaceY { public String geek(); } |
现在,假设我们有一个实现这两个接口的类:
public class Testing implements InterfaceX, InterfaceY { public String geek() { return "hello" ; } } |
问题是: 一个java类能否使用具有相同签名但返回类型不同的相同方法实现两个接口?? 不,这是个错误 如果两个接口包含具有相同签名但不同返回类型的方法,则不可能同时实现这两个接口。 根据 JLS(§8.4.2) 在这种情况下,不允许使用具有相同签名的方法。
Two methods or constructors, M and N, have the same signature if they have, the same name the same type parameters (if any) (§8.4.4), and after adopting the formal parameter types of N to the type parameters of M, the same formal parameter types.
在一个类中声明两个具有重写等效签名的方法是编译时错误。
// JAVA program to illustrate the behavior // of program when two interfaces having same // methods and different return-type interface bishal { public void show(); } interface geeks { public int show(); } class Test implements bishal, geeks { void show() // Overloaded method based on return type, Error { } int show() // Error { return 1 ; } public static void main(String args[]) { } } |
输出:
error: method show() is already defined in class Test error: Test is not abstract and does not override abstract method show() in geeks error: show() in Test cannot implement show() in bishal
// Java program to illustrate the behavior of the program // when two interfaces having the same methods and different return-type // and we defined the method in the child class interface InterfaceA { public int fun(); } interface InterfaceB { public String moreFun(); } class MainClass implements InterfaceA, InterfaceB { public String getStuff() { return "one" ; } } |
error: MainClass is not abstract and does not override abstract method fun() in InterfaceA
本文由 比沙尔·库马尔·杜比 .如果你喜欢GeekSforgek,并想贡献自己的力量,你也可以使用 贡献极客。组织 或者把你的文章寄到contribute@geeksforgeeks.org.看到你的文章出现在Geeksforgeks主页上,并帮助其他极客。
如果您发现任何不正确的地方,或者您想分享有关上述主题的更多信息,请写下评论。
© 版权声明
文章版权归作者所有,未经允许请勿转载。
THE END