First, understand what is called polymorphism:
The same operation acts on different objects, can have different interpretations, produce different execution results, which is polymorphism. To give an example of an image, when we listen to a concert, when the conductor signals the beginning, different instruments receive the same signal, but they produce different behaviors: The piano is the sound of the pianos, the trumpet is the trumpet. Or, if each animal is treated as an object, then they have a method called eating, but they have different behaviors.
Second, the realization of polymorphism.
In C #, polymorphism is implemented by using a derived class to override a virtual-function method in a base class. So how do you write virtual functions?
The method of the base class is to be rewritten by adding the keyword virtual to the virtual method to achieve the most important feature of object-oriented polymorphism, that is, the base class can use the method of the derived class.
[CSharp]View PlainCopy
- Public class Animal
- {
- public virtual void Eat ()
- {
- Console.WriteLine ("Eat something");
- }
- }
[CSharp]View PlainCopy
- Public class Cat:animal
- {
- public override void Eat ()
- { //completely Replace base class method
- Console.WriteLine ("Eat small fishes!");
- }
- }
- Public class Dog:animal
- {
- public override void Eat ()
- { //completely Replace base class method
- Console.WriteLine ("Eat small bones!");
- }
- }
[CSharp]View PlainCopy
- static void Main (string[] args)
- {
- Animal mycat = new Cat ();
- Animal Mydog = new Dog ();
- Mycat. Eat ();
- Mydog. Eat ();
- }
The results of the operation are as follows:
Polymorphism in C #