Java InstanceOf

Understanding instanceOf working in Java



SuperClassA  reference  = new  SubClassAInSamePackage();
if(reference instanceof SuperClassA){
   // some logic 

instanceOf operator validation is done both at Compile time and Run Time.


At compile Time :

Type of reference (left side) is validated against the Class (Right Hand side) to see if the condition is even possible .

if(reference instanceof String) results in compile time error as in this case reference type SuperClassA is not related to String Type(any parent child relationship).

At Run Time :

At run time the Object referred by the reference(Left hand side ) is validated to the class (Right hand side).
Reference can assume any object at runTime , either object of the Type the reference is or subType of the type of reference