简体   繁体   中英

How to find out which interface a method was called on?

I have a simple Java question. Consider the following interfaces:

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

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

So when a class is going to implement them, it should be like this:

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

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

My question is, in work method, how would I find out that, it has invoked by type A or B ?

The above class in C# would be like this, and this separates both implementations very well:

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

But how would I achieve something like C# model in Java?!

Thanks in advance.

Neither. The idea of an interface is that a class that implements it, agrees with the "contract" the interface implies. If you have two interfaces, requiring both to implement a method work() , and a class that implements both interfaces, then it has to implement work() to agree with the contract of both.

The JavaDoc says:

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.

And that is exactly what you do by implementing a work() method: you satisfy both interfaces A and B .

Your interface only tells you the signatures of the methods that the implementing class needs to provide. In your example both A and B ask for a method work() that has void as return type. So basically they are both asking for the same method. I don't see how you could or would need to differentiate?

You might have a problem with diamand implementation. You need to specified it by your own.

void work() { A.super.work(); } // or B.super.work();

The method work will satisfy the requirements of both interfaces. The method is contained on the class, which can instantiate both interfaces. In order to implement the interface the class must possess the methods specified in the interface. It does not matter if the same method is used to satisfy the requirements of multiple interfaces.

JVM will not be invoking A or B, but only the implementation Impl. You can cast back to A or B and your client can invoke methods based on the methods available in the specific interface.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM