/*** 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