如何在java中实现具有相同签名的已实现接口的重写方法。并为每个接口给出不同的实现
假设我有两个具有相同方法签名的接口 InterfaceA 和 InterfaceB。 InterfaceA:
public interface InterfaceA {
void printInterfaceName();
}
和 InterfaceB:
public interface InterfaceB {
void printInterfaceName();
}
我有一个正在实现这两个接口的打印类 打印类:
public class Printing implements InterfaceA, InterfaceB {
// want to override the printInterfaceName() method such way
// so that it will give an output which given in main method comment
}
我有一个带有 main 方法的 Main 类
public class Main {
public static void main(String[] args) {
InterfaceA a = new Printing();
InterfaceB b = new Printing();
a.printInterfaceName(); // this is should print `INTERFACE-A`
b.printInterfaceName(); // and this is should print `INTERFACE-B`
}
}
Let's say I have two interfaces InterfaceA and InterfaceB with the same method signature.
InterfaceA:
public interface InterfaceA {
void printInterfaceName();
}
And InterfaceB:
public interface InterfaceB {
void printInterfaceName();
}
And I have a Printing class that is implementing both the interface
Printing class:
public class Printing implements InterfaceA, InterfaceB {
// want to override the printInterfaceName() method such way
// so that it will give an output which given in main method comment
}
And I have a Main class with a main method on it
public class Main {
public static void main(String[] args) {
InterfaceA a = new Printing();
InterfaceB b = new Printing();
a.printInterfaceName(); // this is should print `INTERFACE-A`
b.printInterfaceName(); // and this is should print `INTERFACE-B`
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
由于该方法不知道上下文(a.printInterfaceName() 或 b.printInterfaceName()),因此无法区分它们并打印 INTERFACE-A 或 接口-B。
据我所知,反射和instanceof都无法做到这一点。在接口中使用默认方法也不起作用。
也许你可以写更多关于你的意图,以便可以提出不同的解决方案?
Since the method is not aware of the context (a.printInterfaceName() or b.printInterfaceName()), it will not be possible to distinguish between both of them and print INTERFACE-A or INTERFACE-B.
As far as I know, neither reflection nor instanceof can do the trick. Having default Methods in the Interfaces wont work either.
Maybe you can write more about your intention, so that a different solution can be suggested?