12.1 polymorphic-Four characteristics12.1.1Concept
The so-called polymorphic, refers to a reference (type) in different situations in a variety of states.
It can be understood that polymorphism refers to a method that is implemented in a different subclass by pointing to a pointer to the parent class.
12.1.2 Precautions
In explaining polymorphism, we noticed a phenomenon - type conversion.
1. Java allows a reference variable of the parent class to refer to an instance of its subclass (object)
Animal animal=new Cat ();
2, there are some details about type conversion requirements, such as whether the subclass can be converted to a parent class, what requirements and so on ...
Polymorphic Code Demo:
1 /**Date: 2016-03-042 * Function: Multi-state demo3 */4 Public classPractice5 {6 Public Static voidMain (String []args)7 {8Master master=NewMaster ();9Master.feed (NewCat (),NewFish ());//calling subclassesTen } One } A - classMaster//class owner - { the Public voidFeed (Animal Animal, food food)//Polymorphic method that can invoke subclasses with the parent class, - //Here the code can be added to the sub-class when it is not moving, very convenient - { - animal.getname (); + food.eat (); - } + } A at classAnimal//The parent class animal - { - String name; - Public voidGetName () - { -System.out.println ("Don't know what the animal is!" "); in } - } to + classCatextendsAnimal//Animals of the sub-category cat - { the Public voidGetName () * { $System.out.println ("This is a cat!") ");Panax Notoginseng } - } the + classDogextendsAnimal//the animal's sub-type dog A { the Public voidGetName () + { -System.out.println ("This is a dog!") "); $ } $ } - - classFood//Food of the parent class the { - String name;Wuyi Public voidEat () the { -System.out.println ("Don't know what food!" "); Wu } - } About $ classFishextendsFood//Food of the sub-type fish - { - Public voidEat () - { ASystem.out.println ("Cats love to eat fish!") "); + } the } - $ classBoneextendsFood//Child bones of food the { the Public voidEat () the { theSystem.out.println ("Dog loves bones!") "); - } in}
Operation Result:
1 this is a cat! 2 cats love to eat fish!
Hanshunping-Step Learning Java 12th polymorphism