[英]Two interfaces with same method name, what happens when I override?
So I have a class 'MyClass' & two interfaces 'A' & 'B' 所以我有一个'MyClass'类和两个接口'A'和'B'
public class MyClass implements A, B {
@Override
public void mymethod(){
System.out.println("hello world");
}
}
... ...
public interface A {
void mymethod();
}
... ...
public interface B {
void mymethod();
}
What method from what interface here is being overridden? 从这个界面覆盖什么方法被覆盖?
I'm thinking both are? 我在想两个都是?
Thanks (student) 谢谢(学生)
In this case it will be like there is only one method. 在这种情况下,它就像只有一种方法。 It will override "both" methods in this case because they have the exact same signatures. 在这种情况下,它将覆盖“两个”方法,因为它们具有完全相同的签名。 If the methods had different signatures (return type or something) then there would be a problem. 如果方法有不同的签名(返回类型或某些东西),那么就会出现问题。 Check out this answer here 在这里查看这个答案
For Example: 例如:
public class MyClass implements A, B {
@Override
public void mymethod(){
System.out.println("hello world");
}
}
...
public interface A {
void mymethod();
}
...
public interface B {
String mymethod();
}
This would cause a problem... 这会导致问题......
这既是因为它符合两个接口。
((A)(new MyClass())).mymethod();
((B)(new MyClass())).mymethod();
outputs 输出
hello world
hello world
It's straightforward to test what can happen. 测试可能发生的事情很简单。
If you encounter this then there's potentially some common feature between A and B that could be abstracted to another interface that A and B both extend, or there's undesirable shared terminology between them causing the overlap and something might need renamed. 如果遇到这种情况,那么A和B之间可能会有一些共同特征被抽象到A和B都扩展的另一个接口,或者它们之间存在不合需要的共享术语导致重叠并且可能需要重命名。
An interface is just a contract. 界面只是一个契约。
Implementing A means MyClass
should have a method void mymethod()
. 实现A意味着MyClass
应该有一个方法void mymethod()
。
Implementing B means MyClass
should have a method void mymethod()
. 实现B意味着MyClass
应该有一个方法void mymethod()
。
It's overriding "both", but I am not sure this is a proper way to say it. 它凌驾于“两者”之上,但我不确定这是说出来的正确方法。
It's just about filling a contract and making sure MyClass has the proper method. 这只是填写合同并确保MyClass具有正确的方法。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.