C # basic implementation of Polymorphism

Source: Internet
Author: User

There are two types of polymorphism: Polymorphism at compilation and runtime.

Polymorphism during compilation: The polymorphism during compilation is implemented through overloading. For non-Virtual members, during compilation, the system determines the operation based on the passed parameters, returned types, and other information.

Polymorphism at run time: the polymorphism at run time is not implemented until it is run, according to the actual situation. C # The Running polymorphism is implemented through the reset virtual function.


In C #, it is not easy to tell the polymorphism clearly. It is called with the same name, but different results are displayed. Here is an example to illustrate how polymorphism is implemented.

Subclass inherits the method obtained by the parent class and can be overwritten. In this way, the instance of the parent class can use the subclass method.

Class Program {static void Main (string [] args) {fruit ep; // defines a fruit instance ep = new Apple (); ep. addFruit (5); ep = new Orange (); ep. addFruit (4) ;}} public abstract class fruit // create an abstract class-fruit {private uint nint_Weight; public abstract void AddFruit (uint nWeight);} public class Apple: fruit // create a fruit subclass-Apple {public override void AddFruit (uint nWeight) {Console. writeLine ("You added an apple, quality: {0}", nWeight) ;}} public class Orange: fruit // create a fruit subclass-orange {public override void AddFruit (uint nWeight) {Console. writeLine ("You added an orange, quality: {0}", nWeight );}}



Inheritance: When a subclass inherits the parent class, it can be used directly without redefining the methods in the parent class.

Polymorphism: When the subclass overrides the method of the parent class. The parent class Object selects the base class method as needed when calling the subclass method.


Related Article

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.