When is Java instanceof used?

Source: Internet
Author: User

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?

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.