What are the functions of virtual and override in C #?

Source: Internet
Author: User

Using system;
Class
{
Public ()
{
Printfields ();
}

Public Virtual void printfields ()
{}
}

Class B:
{
Int x = 1;
Int y;
Public B ()
{
Y =-1;
}

Public override void printfields ()
{
Console. writeline ("x = {0}, y = {1}", x, y );
}
}

What is the output when new B () is used to create B's instance?

--------------------------------------------
========================================================== =
X = 1 y = 0

New B () is executed first
Int x = 1;
Int y;
The base class constructor is called when the constructor B is executed.
Public ()
{
Printfields ();
}

The printfields method in a is a virtual method, and the override keyword has been used in B to implement this method.
The printfields method console. writeline ("x = {0}, y = {1}", x, y) In subclass B is executed );
// Note that the constructor B is not executed yet, so the value of Y is 0.

Then execute the constructor to B // At this time x = 1 y =-1;

The virtual modifier is a virtual method, which implies that its subclass should have its own implementation.

The override modifier is an override method, which overwrites the implementation of the original methods of the base class.
Virtual modification method

In addition to override, its subclass can be modified using new.

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.