Next, an example is given to deepen the impression on polymorphic issues:
Cat and dog case.
/* polymorphic exercise: Cat and dog case */class Animal {public void Eat () {System.out.println ("eat");}} Class Dog extends Animal {public void Eat () {System.out.println ("Dog eats Meat");} public void Lookdoor () {System.out.println ("dog Janitor");}} Class Cat extends Animal {public void Eat () {System.out.println ("Cat eats Fish");} public void PlayGame () {System.out.println ("Cat Hide and Seek");}} Class Duotaitest {public static void main (string[] args) {//defined as dog animal a = new dog (); System.out.println (a);////[email protected]a.eat ();//Dog eats meat System.out.println ("--------------");//reverts to dog D = ( DOG) a;//downward transition System.out.println (a);//[email protected]system.out.println (d);//[email protected]d.eat ( );//The Dog Eats meat d.lookdoor (); System.out.println ("--------------");//become Cat A = new Cat (); System.out.println (a);//Reassign the address to re-open the memory space [Email protected]d.eat ();//The object of the dog has not changed. A.eat (); System.out.println ("--------------");//reduced to cat cat C = (cat) A; System.out.println (a);//[email protected]system.out.println (c);//[email protected]c.eat (); c.playgame (); System.out.println ("--------------");//Demo error content//dog dd = new Animal ();//animals are dogs! Error! Error//dog DDD = new Cat ();//cat is a dog! Error//classcastexception//dog DD = (dog) a;//a already belongs to the cat, cannot force the cat to be converted to dog a = new dog ()//Can reallocate memory space, this time is no longer the previous address, not [email Protected]system.out.println (a);//Allocate new memory space once again [email protected]}}//additional polymorphism also has the benefit that the variable A that defines the reference class once can be used all the time.
Believe polymorphism is what, and polymorphic use of the way at a glance. There are problems to be discussed together below.
The object-oriented (polymorphic exercise) of the first season of getting Started with Java