instanceof operator

  • Summary

  1. Check instanceof whether type transition is possible or not.

2. Type transition

3. instanceof parent returns true, but it does NOT mean fe is Object or Car!

4. Why doing reference type transition? By modifying reference type variable(remote control), able to control the number of usable members.

FireEngine f = new FireEngine();//the number of usable members : 5
Car c = (Car)f;//CONTROL the number of usable members:4.
  1. Check the type transition is possible. if it is possible, return true.

Before type transition, MUST check instanceof before type transition.

//To use the function(method) of instance.
//Car type 'c' CANNOT call water();

//Change 
void doWork(Car c) {
    if(c instanceof FireEngine) {
        FireEngine fe = (FireENgine)c;
        fe.water();
    }
}

instanceof for parent and itself returns true.

FireEngine < Car < Object

fe instanceof Object/Car is true, but it does NOT mean fe is Object or Car. But it means type transition is possible.

FireEngine fe = new FireEngine();
System.out.println(fe instanceof Object);.//fe indicates Object?true.
System.out.println(fe instanceof Car);//fe indicates Car?true.
System.out.println(fe instanceof FireEngine);//fe indicates FireEngine?true.(itself)

Last updated