Reputation:
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.
Upvotes: 4
Views: 1465
Reputation: 2668
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();
Upvotes: 3
Reputation: 509
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.
Upvotes: 2
Reputation: 94499
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.
Upvotes: 2
Reputation: 3822
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?
Upvotes: 3
Reputation: 68897
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
.
Upvotes: 6