Here casually talk about polymorphism, read the above inheritance and then look at this article.
Polymorphism: The same method is called by the different objects implemented by the inheritance, showing different behavior.
The previous foreground call code is as follows:
1 namespaceConsoleApplication72 {3 class Program4 {5 Static voidMain (string[] args)6 {7Dog dog =NewDog ();8Dog. Name ="Bones";9 Dog. Show ();Ten //Output Results//Puppies like to eat: Bones One A -Cat cat =NewCat (); -Cat. Name ="Fish"; the Cat. Show (); - //Output Results//Kittens like to eat: Fish - -Mouse Mouse =NewMouse (); +Mouse. Name ="Rice"; - Mouse. Show (); + //Output Results//mice like to eat: Fish A atPanda Panda =NewPanda (); -Panda. Name ="Bamboo"; - Panda. Show (); - //Output Results//pandas like to eat: Fish - - Console.readkey (); in - } to } +}
As you can see, every animal class is an object.
Dog's target: Dog
Cat's object: Cat
Object of the mouse: mouse
Panda's object: Panda
For these animals to implement the show () method, you declare each object, which says, polymorphism is: different objects invoke the same method, showing different behavior.
And all sorts of animal classes inherit the animal class, and the code goes like this:
1 namespaceConsoleApplication72 {3 Public classAnimal4 {5 protected stringname;6 Public stringName7 {8 Get{returnname;}9 Set{name ="Fresh."+value;}Ten } One Public Virtual voidShow () A { -Console.WriteLine ("I'm the father of all kinds of animals."); - } the } - - Public classCat:animal - { + Public Override voidShow () - { +Console.WriteLine ("Kittens like to eat:"+name); A } at } - - Public classDog:animal - { - Public Override voidShow () - { inConsole.WriteLine ("Kittens like to eat:"+name); - } to } + - Public classMouse:animal the { * Public Override voidShow () $ {Panax NotoginsengConsole.WriteLine ("mice like to eat:"+name); - } the } + A Public classPanda:animal the { + Public Override voidShow () - { $Console.WriteLine ("pandas like to eat:"+name); $ } - } - the}
Front Code:
1 namespaceConsoleApplication72 {3 class Program4 {5 Static voidMain (string[] args)6 {7 8 Animal Animal;9Animal =NewDog ();TenAnimal. Name ="Bones"; One Animal. Show (); A -Animal =NewCat (); -Animal. Name ="Fish"; the Animal. Show (); - -Animal =NewMouse (); -Animal. Name ="Rice"; + Animal. Show (); - +Animal =NewPanda (); AAnimal. Name ="Panda"; at Animal. Show (); - - Console.readkey (); - - } - } in}
Results:
Puppies like to eat: fresh bones
Kittens like to eat: fresh fish
Rats like to eat: fresh rice
Pandas like to eat: fresh bamboo
Animal objects are assigned different instances, but animal only call the show () method to get different results.
C # polymorphism (popular understanding)