如何在java中实现具有相同签名的已实现接口的重写方法。并为每个接口给出不同的实现

发布于 2025-01-08 23:54:52 字数 862 浏览 5 评论 0原文

假设我有两个具有相同方法签名的接口 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

帅的被狗咬 2025-01-15 23:54:52

由于该方法不知道上下文(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?

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文