The instanceof in Java is used to determine if an instance is an instance of a class.
Example: a instanceof B (A is an instance, B is a class name)
If a is an instance of B, then: (a instanceof B) ==true and vice versa ==false
code example:
Package Javakeywords;class bird{//Parent class}class Bigbird extends Bird{//bird subclass}class Littlebird extends Bird implements Birdfly{//bird sub-class plus Birdfly interface}interface Birdfly{}public class Javakwinstanceof {public static void main (string[] args) {//TODO auto-generated method stub javakwinstanceof mythis=new javakwinstanceof (); Bird mybird=new Bird (); Bigbird mybigbird=new Bigbird (); Littlebird mylittlebird=new Littlebird (); Print the relationship between each instance and class PRT (Mythis instanceof javakwinstanceof);//Print Result: Yes PRT (Mybird instanceof Bird);//print Result: YES PRT (Mybigbird instanceof Bird);//Print Result: YES sub-class instance out of the object is also the parent class instance PRT (Mybird instanceof Bigbird);//print Result: NO The object of the parent class instance is not an instance of a subclass PRT (Mylittlebird instanceof Bird);//Print Result: The object that is instantiated after the YES subclass plus other interfaces is also an instance of the parent class */* PRT (Myli Ttlebird instanceof Bigbird);//Compile error There is no instanceof relationship between the two classes that have no inheritance relationship * PRT (1 instanceof int);//Compilation errors */}//Determine and show if a is an instance of B static void PRT (Boolean A_is_instanceof_b) {if (a_is_instanceof_b) {System.out.println ("YES"); } else{System.out.println ("NO"); } }}
Output Result:
Java:instanceof usage