[英]Two interfaces require to implement the method with the same name
If two interfaces require to implement the method with the same name, then the method() is called twice. 如果两个接口要求用相同的名称实现该方法,则method()会被调用两次。 I need 2 methods implemented for 2 different interfaces, how can I implement both of them to do different things?
我需要为2个不同的接口实现2种方法,如何才能同时实现这两种方法以完成不同的工作?
public class MainClass implements BarObj.BarInt, FooObj.FooInt{
MainClass(){
}
void trigger()
{
new BarObj(this);
new FooObj(this);
}
@Override
public void method() {
System.out.println("I DONT KNOW WHICH METHOD");
}
public static void main(String[] args) {
new MainClass().trigger();
}
}
public class BarObj {
interface BarInt
{
void method();
}
public BarObj(BarInt _barInt)
{
_barInt.method();
}
}
public class FooObj {
interface FooInt
{
public void method();
}
public FooObj(FooInt _fooInt)
{
_fooInt.method();
}
}
You can't 你不能
But to solve your problem you can do next. 但是要解决您的问题,您可以下一步进行。
implements BarObj.BarInt, FooObj.FooInt
implements BarObj.BarInt, FooObj.FooInt
method
method method
方法 trigger
method trigger
方式 It should look like this 它应该看起来像这样
void trigger()
{
new BarObj(new BarObj.BarInt(){
@Override
public void method() {
System.out.println("NOW I DO KNOW WHICH METHOD");
System.out.println("I'm bar");
}
});
new FooObj(new FooObj.FooInt(){
@Override
public void method() {
System.out.println("NOW I DO KNOW WHICH METHOD");
System.out.println("I'm foo");
}
});
}
It use anonymous class you can google for more detail. 它使用匿名类,您可以在Google上搜索更多详细信息。
You can not have two methods with same name and same argument type and length in one class. 在一个类中,不能有两个名称相同,参数类型和长度相同的方法。 When you implement two interfaces that have methods with same name, you need to give the implementation to only one method that acts as to be implemented for both interfaces because the methods in interfaces are empty and will never be executed.
当实现两个具有相同名称的方法的接口时,由于接口中的方法为空并且永远不会执行,因此您只需将实现仅赋予一个要为两个接口都实现的方法。 What will be executed is your class method that has been Overrided from the interfaces.
将执行的是已从接口重写的类方法。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.