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.
Entityreference that could hold any subclass at any time?
instanceof operator is used in comparisons - it gives a
when used to compare an object reference with a class name.
referenceExpression instanceof ObjectType
trueif the reference points to an instance of that class.
trueif the object is a derived class of the one tested.
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).
if (e[i] instanceof Wizard) ((Wizard) e[i]).castSpell();
There is another method of testing:
getClass()method that returns a
Classobject that uniquely identifies each class.
classpseudo-property that provides the same
Classobject as above; this object is the class as loaded into the JVM (technically,
classisn't a field, but syntax-wise it is treated somewhat like a
if (e[i].getClass().equals(Wizard.class)) ((Wizard) e[i]).castSpell();