Checking an Object's Type: Using instanceof

Contact Us or call 1-877-932-8228
Checking an Object's Type: Using instanceof

Checking an Object's Type: Using instanceof

Given that you can have base class references to several different derived class types, you will eventually come to a situation where you need to determine exactly which derived class is referenced - you may not know it at the time the program is compiled.

  • In the above example, perhaps wizards, ogres, trolls, etc. have their own special methods.
  • How would you know which method to call if you had an Entity reference that could hold any subclass at any time?

The instanceof operator is used in comparisons - it gives a boolean answer when used to compare an object reference with a class name.

referenceExpression instanceof ObjectType
  • It will yield true if the reference points to an instance of that class.
  • It will also give true if the object is a derived class of the one tested.
  • If the test yields true, then you can safely typecast to call a derived class method (you still need to typecast to call the method - the compiler doesn't care that you performed the test).

For example:

if (e[i] instanceof Wizard) ((Wizard) e[i]).castSpell();

There is another method of testing:

  • Every object has a getClass() method that returns a Class object that uniquely identifies each class.
  • Every class has a class pseudo-property that provides the same Class object as above; this object is the class as loaded into the JVM (technically, class isn't a field, but syntax-wise it is treated somewhat like a static field).
  • With this method, a derived class object's class will compare as not equal to the base class.
if (e[i].getClass().equals(Wizard.class))
	((Wizard) e[i]).castSpell();
  • It is rare that you would need this type of test.
Next