Sandah Aung
Sandah Aung

Reputation: 6188

Using if to select between a super type and a subtype

If I have two classes namely SuperType and SubType where SubType extends SuperType, can I use if to detect the exact type at runtime?

My solution which does not work is as follows:

if (t instanceof SubType) 
    do SubType stuff
else
    do SuperType stuff

Upvotes: 0

Views: 147

Answers (5)

peter.petrov
peter.petrov

Reputation: 39477

You can e.g. use the Reflection API.

if (SubType.class.isInstance(t)){
    // do SubType stuff
}else{
    // do SuperType stuff
}

More details here:

Class.isInstance(Object)

Upvotes: 1

Kumar Abhinav
Kumar Abhinav

Reputation: 6675

You should Class getClass() method to detect the exact class at runtime.

if (t.getClass() == SubType.class) 
    do SubType stuff
else if (t.getClass() == SuperType.class) 
   do SuperType stuff
else do your stuff

Upvotes: 0

Solomon Slow
Solomon Slow

Reputation: 27190

What Eran said is true, but using instanceof is a mistake if you can do this instead:

class SuperType {
    void doStuff(...) {
        ...do SuperType stuff...
    }
}

class SubType {
    @Override
    void doStuff(...) {
        ...do SubType stuff...
    }
}

SuperType t = methodThatMayReturnSuperTypeOrSubType(...);

t.doStuff();

Upvotes: 6

Marko Topolnik
Marko Topolnik

Reputation: 200216

Yes, you can use if with an instanceof operator. However, doing so is usually a design smell because such decision should in most cases be left to the method dispatching mechanism. It makes sense if the types involved are not under your control so the option to add a method to those types is not available.

Upvotes: 4

Eran
Eran

Reputation: 393966

You had a typo. It should be instanceof.

The syntax is :

if (t instanceof SubType) {
    //do SubType stuff
} else {
    //do SuperType stuff
}

Upvotes: 2

Related Questions