Java Multi-State demo

Source: Internet
Author: User

/* polymorphic Test 1. The prerequisite classes and classes must be inherited or implemented, and the methods will generally be overwritten by 2. function to improve code extensibility 3. Drawbacks when a parent class reference points to a subclass object, the extensibility is increased, but only the methods available in the parent class are accessible, and methods that are specific to the subclass are not accessible. Access to subclass-specific methods needs to be judged by the INSTANCEOF keyword 4. A reference to a parent class reference or interface points to its own subclass object. Transition up and down */abstract interface animal{     abstract void eat ();    }class dog implements  Animal{    public void eat () {         System.out.println ("Eat dog Food");     }        public  void hunt () {        system.out.println ("hunting");         }    }class cat implements animal{     public void eat () {         System.out.println ("Eat cat food");        }         public void catchfish () {&NBsp;       system.out.println ("Catch fish");             }    }class DuoTaiDemo{     Public static void main (String[]args) {        function ( New cat ());//equals Animal a = new cat (); promotes subclasses to parent class, up transformation              }        public static  Void function (animal a) {        a.eat ();         if (A instanceof cat) {             Cat c =  (Cat) a;//a reference to a parent class to a subclass object              c.catchfish ();             }else if(A instanceof dog) {            dog d =  (Dog) a;// Convert a reference from a parent class to a subclass Object             d.hunt ();         }    }    }


This article from "Sima" blog, declined reprint!

Java Multi-State demo

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.