Todd Davies
Todd Davies

Reputation: 5522

Checking class of an instance in Java

How do I see if a class overrides another class?

For example: Say bob was a Bot, a class which overrides the abstract class Unit. How can I make the following evaluate to true?

bob.getClass() == Unit.class

Upvotes: 1

Views: 71

Answers (2)

case
case

Reputation: 124

If the implementation is

Bob implements Unit 

then

bob.getClass().getSuperclass() 

will return Unit

Upvotes: 1

Phil K
Phil K

Reputation: 5369

Use the instanceof operator:

if(bob instanceof Unit) {
    // ...
}

Note that once you are certain an object is an instance of a class by using instanceof, you can safely cast it to that class like so:

if(bob instanceof Unit) {
    Unit bobUnit = (Unit) bob;
    bobUnit.unitMethod();
}

This may be necessary when calling a function that only the subclass (e.g. Unit) has a definition of.

Upvotes: 7

Related Questions