Instanceof is a two-dollar operator (operator) of Java and is a reserved keyword for java. Its function is to determine whether its left object is an instance of its right class, and returns a Boolean type of data. Use it to determine whether an object is an instance of a class.
Usage:
Boolean result = Object instanceof class
Parameters:
The Result:boolean type.
Object: Required option. An arbitrary object expression.
Class: Required option. Any of the defined object classes.
Description
Returns True if the object is an instance of the class. Returns False if the object is not an instance of the class, or if object is null.
Example:
Package com.instanceoftest; Interface a {} class B implements a {}//b is a 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}
}
instanceof usage in Java