Parent class variable access subclass methods in Java need to use type conversion (instenceof) keyword/type judgment/

Source: Internet
Author: User

Accessing methods through array elements only accesses methods defined in animal,

The methods defined in tiger and fish cannot be called, such as Statement Animal[2].swim (); When

A type conversion is required to access these methods, as shown in the following procedure.

1  Public classdynamicmethoddemo2{2  Public Static voidMain (String args[]) {3Animal []animal=Newanimal[3];4animal[0]=NewAnimal ();5animal[1]=NewTiger ();6animal[2]=NewFish ();7DynamicMethodDemo2 dm=NewDynamicMethodDemo2 ();8Dm.move (animal[0]);9Dm.move (animal[1]);TenDm.move (animal[2]); One } A voidMove (Animal Animal) { - //making judgments about object types - if(Animal instanceof Tiger) the (Tiger) animal). Tigerrun (); - Else if(Animal instanceof Fish) - (Fish) animal). Swim (); - Elseanimal.sleep (); + } -}

Mainly look at the move method, themove method first determine which class object is the animal object, by the judge to perform a different

Method. The instanceof operator is used in the judging process , which is an operator used to determine the type of an object. When judging

After its type, the type conversion is made, and the original type can be called to invoke its class-specific method.

Parent class variable access subclass methods in Java need to use type conversion (instenceof) keyword/type judgment/

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.