Polymorphism in C #

Source: Internet
Author: User

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 
    1. Public class Animal
    2. {
    3. public virtual void Eat ()
    4. {
    5. Console.WriteLine ("Eat something");
    6. }
    7. }

[CSharp]View PlainCopy  
  1. Public class Cat:animal
  2. {
  3. public override void Eat ()
  4. { //completely Replace base class method
  5. Console.WriteLine ("Eat small fishes!");
  6. }
  7. }
  8. Public class Dog:animal
  9. {
  10. public override void Eat ()
  11. { //completely Replace base class method
  12. Console.WriteLine ("Eat small bones!");
  13. }
  14. }

[CSharp]View PlainCopy  
    1. static void Main (string[] args)
    2. {
    3. Animal mycat = new Cat ();
    4. Animal Mydog = new Dog ();
    5. Mycat. Eat ();
    6. Mydog. Eat ();
    7. }

The results of the operation are as follows:

Polymorphism in C #

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.