Java instanceof Usage Details, javainstanceof
Instanceof is a binary operator (operator) of Java and a reserved keyword of Java. It is used to determine whether the object on the left is an instance of the class on the right, and return boolean data. It is used to determine whether an object is an instance of a Class.
Usage:
Boolean result = object instanceof class
Parameters:
Result: boolean type.
Object: required. Any object expression.
Class: required. Any defined object class.
Note:
If this object is an instance of this class, true is returned. If the object is not an instance of the class, or the object is null, false is returned.
Example:
Package com. instanceoftest; interface A {} class B implements A {}// B is the implementation of class C extends B {}// C inherits B class D {} class instanceoftest {public static void main (string [] args) {A a = null; B B = null; boolean res; System. out. println ("instanceoftest test case 1: ------------------"); res = a instanceof A; System. out. println ("a instanceof A:" + res); // a instanceof A: false
Res = B instanceof B;
System. out. println ("B instanceof B:" + res); // B instanceof B: false System. out. println ("\ ninstanceoftest test case 2: ------------------"); a = new B (); B = new B (); res = a instanceof A; System. out. println ("a instanceof A:" + res); // a instanceof A: true res = a instanceof B; System. out. println ("a instanceof B:" + res); // a instanceof B: true res = B instanceof A; System. out. println ("B instanceof A:" + res); // B instanceof A: true res = B instanceof B; System. out. println ("B instanceof B:" + res); // B instanceof B: true System. out. println ("\ ninstanceoftest test case 3: ------------------"); B b2 = new C (); res = b2 instanceof A; System. out. println ("b2 instanceof A:" + res); // b2 instanceof A: true res = b2 instanceof B; System. out. println ("b2 instanceof B:" + res); // b2 instanceof A: true res = b2 instanceof C; System. out. println ("b2 instanceof C:" + res); // b2 instanceof A: true System. out. println ("\ ninstanceoftest test case 4: ------------------"); D d = new D (); res = d instanceof A; System. out. println ("d instanceof A:" + res); // d instanceof A: false res = d instanceof B; System. out. println ("d instanceof B:" + res); // d instanceof B: false
Res = d instanceof C; System. out. println ("d instanceof C:" + res); // d instanceof C: false
Res = d instanceof D; System. out. println ("d instanceof D:" + res); // d instanceof D: true}
}