Inheritance of the manifestation of Java polymorphism

Source: Internet
Author: User

/*** Function: Demo polymorphic*/ PackageCom.litao; Public classDemo5 { Public Static voidMain (string[] args) {//TODO auto-generated Method Stub//Multi-state representation        /*Cat cat1 = new Cat ();                Cat1.cry ();        Dog dog = new Dog (); Dog.cry ();*/        //automatically determine what type of reference is on the right//all instances of subclasses or grandchildren are given a parent class to refer to//Animal Animal = new Cat ();//        //if the cat has cry method, then the cat cry, otherwise animal cry//animal.cry ();//        //animal = new Dog ();//animal.cry ();Master Master=NewMaster (); Master.feed (NewDog (),NewBone ()); Master.feed (NewCat (),NewFish ()); }}//Lord Humanclassmaster{//Feeding Animals     Public voidFeed (Animal an, food f) {an.eat ();    F.showname (); }}classfood{String name;  Public voidShowName () {}}classFishextendsfood{ Public voidShowName () {System.out.println (Fish); }}classBoneextendsfood{ Public voidShowName () {System.out.println (Bones); }}//Animal Class Animalclassanimal{String name; intAge ;  PublicString GetName () {returnname; }     Public voidsetName (String name) { This. Name =name; }     Public intGetage () {returnAge ; }     Public voidSetage (intAge ) {         This. Age =Age ; }        //animals will call     Public voidcry () {System.out.println ("Don't know how to call ..."); }         Public voideat () {System.out.println ("I don't know what I like to eat."); }}classDogextendsanimal{//The cat called himself     Public voidcry () {System.out.println ("Wang Wang called"); }        //animals can eat.     Public voideat () {System.out.println ("Dogs like to eat bones."); }}classCatextendsanimal{//The cat called himself     Public voidcry () {System.out.println ("Cat's name."); }         Public voideat () {System.out.println ("Cats like to eat fish."); }}

Inheritance of the manifestation of Java polymorphism

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.