One application that I personally understand is that when you get a reference to an object (such as a parameter), you might want to judge the class that the reference really points to. So you need to start at the bottom of the tree and use the instanceof operator to judge that the first class that evaluates to TRUE is the one that the reference really points to.
For example, the following example:
classperson{}classStudentextendsperson{}classPostgraduateextendsstudent{}classanimal{} Public classInstanceoftester { Public Static voidMain (string[] args) {instanceoftest (NewStudent ()); } Public Static voidinstanceoftest (person p) {//determine the True type of P if(pinstanceofpostgraduate) {System.out.println ("P is an instance of class postgraduate"); } Else if(pinstanceofStudent) {System.out.println ("P is an instance of class student"); } Else if(pinstanceofPerson ) {System.out.println ("P is an instance of a class person"); } Else if(pinstanceofObject) {System.out.println ("P is an instance of class object"); } /*if (P instanceof Animal) {//This wrong compilation error, so make a comment System.out.println ("P is an instance of Class Animal"); }*/ } }
The output of this program is: P is an instance of class student
The inheritance tree where the person class resides is: Object<--person<--student<--postgraduate.
This example also joins a animal class, which is not in the tree of the person class, so it cannot be used as the right operand of the instanceof.
When is Java instanceof used?