Reputation: 150
I have a basic question with Java interfaces.
Say if I have a interface IA
and interface IB extends IA
now,
class CK implements IB,
class CL implements IB,
class CM implements IB,
... etc
void foo(IA iFace) {
// I know how to check if iFace is of type CK/CL/CM ...
// Is it possible to check if iFace is of type IB ?
}
Hope my question is clear.
Thanks for any replies.
Upvotes: 0
Views: 507
Reputation: 55
Use instanceof as follows:
if(ObjectA instanceof ObjectB)
{
//hooray, it is
}
Bear in mind that if B extends A, and you have K, L, M implementing B, they are an instance of B and A.
When you extend a class, you inherit from it and everything it has inherited from.
Upvotes: 0
Reputation: 1500515
You can check using instanceof
:
if (iFace instanceof CK)
etc
... but it's generally a sign that your design has gone wrong, if you have to handle things differently. The idea of the interface should be that you can treat them all the same way, and let the implementations behave differently in an appropriate way.
It doesn't always work out that way, so sometimes instanceof
is the best you can do, but that should be a rarity.
Upvotes: 9