Java instanceof Keywords

Source: Internet
Author: User
instanceof its role is to determine whether an object is a class or interface type. Because the Java language polymorphism allows you to assign an instance of a subclass to a variable of a parent class, but in some cases you need to determine the original type of the variable, you can use the instanceof implementation at this point. The sample code is as follows:

/**

* Define Animal Parent class

*/

Class animal{

}

/**

* Define Animal Subclass Dog

*/

Class Dog extends animal{

public void F1 () {

System.out.println ("woof woof");

}

}

/**

* Define animal Subclass Cat

*/

Class Cat extends animal{

public void F2 () {

System.out.println ("Miao Miao");

}

}

/**

* Define test class tests

*/

public class test{

public static void Main (string[] args) {

Dog d = new Dog ();

Show (d);

Cat C = new Cat ();

Show (c);

}

Define the parameters of the Show method using polymorphic features to improve the flexibility of the parameters

public static void Show (Animal a) {

if (a instanceof Dog) {

Dog Dog = (Dog) A;

DOG.F1 ();

}else if (a instanceof Cat) {

Cat cat = (cat) A;

Cat.f2 ();

}

}

}

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.