The instanceof operator in Java is used to indicate at run time whether an object is an instance of a particular class.
Instanceof Indicates whether this object is an instance of this particular class or its subclasses by returning a Boolean value.
Usage: Result = Object instanceof class
Parameters:
Result: Boolean type.
Object: Required option. An arbitrary object expression.
Class: Required option. Any of the defined object classes.
Description: If object is an instance of class, the instanceof operator returns TRUE. Returns False if object is not an instance of the specified class, or if object is null.
Examples are as follows:
1 Packagecom.instanceoftest;2 3 4 5 Interfacea{}6 classBImplementsa{7 8 }9 classCextendsB {Ten One } A - classInstanceoftest { - Public Static voidMain (string[] args) { theA a=NULL; -B b=NULL; - BooleanRes; - +System.out.println ("Instanceoftest test Case 1:------------------"); -res = ainstanceofA; +System.out.println ("A instanceof A:" +res); A atres = binstanceofB; -System.out.println ("b instanceof B:" +res); - -System.out.println ("/ninstanceoftest test Case 2:------------------"); -A=NewB (); -b=NewB (); in -res = ainstanceofA; toSystem.out.println ("A instanceof A:" +res); + -res = ainstanceofB; theSystem.out.println ("A instanceof B:" +res); * $res = binstanceofA;Panax NotoginsengSystem.out.println ("b instanceof A:" +res); - theres = binstanceofB; +System.out.println ("b instanceof B:" +res); A theSystem.out.println ("/ninstanceoftest test Case 3:------------------"); +B b2= (C)NewC (); - $res = B2instanceofA; $System.out.println ("B2 instanceof A:" +res); - -res = B2instanceofB; theSystem.out.println ("B2 instanceof B:" +res); - Wuyires = B2instanceofC; theSystem.out.println ("B2 instanceof C:" +res); - } Wu } - About $ /* - Result: - - A instanceoftest test Case 1:------------------ + a instanceof a:false the b instanceof B:false - $ instanceoftest test Case 2:------------------ the a instanceof a:true the a instanceof b:true the b instanceof A:true the b instanceof B:true - in instanceoftest test Case 3:------------------ the B2 instanceof A:true the B2 instanceof B:true About B2 instanceof C:true the the the + */
The instanceof operator in Java