java - 如何找出在哪个接口(interface)上调用了方法?

标签 java

我有一个简单的 Java 问题。考虑以下接口(interface):

interface A { 
    void work();
    void a();
}

interface B {
    void work();
    void b();
}

所以当一个类要实现它们时,应该是这样的:

class Impl implements A, B {
    void work() {
        /*some business*/
    }

    void a() {}
    void b() {}
}

我的问题是,在 work 方法中,我如何发现它是由 AB 类型调用的?

C# 中的上述类将是这样的,这很好地将两个实现分开:

class Impl : A, B
{
    void B::work() {}
    void A::work() {}
    void a() {}
    void b() {}
}

但是我如何在 Java 中实现类似 C# 模型的东西呢?!

提前致谢。

最佳答案

都没有。 interface 的想法是实现它的类与接口(interface)暗示的“契约”一致。如果你有两个接口(interface),要求两者都实现一个方法 work(),并且一个类实现这两个接口(interface),那么它必须实现 work() 以符合双方的契约(Contract)。

JavaDoc说:

Implementing an interface allows a class to become more formal about the behavior it promises to provide. Interfaces form a contract between the class and the outside world, and this contract is enforced at build time by the compiler. If your class claims to implement an interface, all methods defined by that interface must appear in its source code before the class will successfully compile.

这正是您通过实现 work() 方法所做的:您同时满足接口(interface) AB

关于java - 如何找出在哪个接口(interface)上调用了方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20317448/

相关文章:

java - 保存从Entity扩展的实例

java - 使用itext java在pdf上叠加图像

java - 为什么 Dalvik 的 HttpURLConnection 中没有重写 getInputStream() ?

java - mysql last_insert_id() 是否适用于连接池?

java - 如何使用 Java 反射来检查 ParameterizedType 参数是否扩展特定类

java - 需要创建 Java JAR 文件并将其添加到 Maven Dependency

java - Android WebView 应用程序在模拟器 : null Application Context? 中崩溃

java - 在kony中链接JavaConnector时发生ClascastException

java - 我正在制作 NLP 应用程序,但模型太大

java - 在每个类继承的 hibernate 表中使用多个选择而不是联合