0

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.

3 Answers 3

9

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.

Sign up to request clarification or add additional context in comments.

Comments

2

you can use the instanceof keyword

1 Comment

aaah. should have thought about it. Thanks!
0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.