Java:instanceof usage

Source: Internet
Author: User

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

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.