C # Object-oriented polymorphism

Source: Internet
Author: User

Because subclasses inherit class parent classes, subclasses have the same behavior, but the behavior of subclasses sometimes needs to be different from each other

Subclasses need to override the parent class's methods to implement the subclass-specific behavior, which is called Polymorphism in C #.

Polymorphism is the same type of object calling the same method but showing a different phenomenon

Implementing overriding methods using the virtual and override keywords

Can be overridden by a derived class only if the base class member is declared as virtual and abstract

If a subclass wants to change the implementation behavior of a virtual method, it must use the Override keyword

The result of the final execution is:

But there is a problem with this code

It is

Animal animal=new Animal ();

This kind of remark is meaningless, because the base class here is to provide a public member for the subclass

Then we can create the base class as an abstract class and take advantage of the abstract keyword to prevent this from happening.

Prevent derived classes from overriding virtual members


Use the sealed keyword to achieve

If you have a class that inherits horse and tries to override the Voice method, you receive an error message

Hide base class members with new members

Use the New keyword to implement

C # Object-oriented polymorphism

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.