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.