Prepaid habits Code :
Code
Using System;
Public Class Myclass
{
Public Static Void Main ()
{
A = New A ();
B = New B ();
Bb = New BB ();
A. Fun ();
B. Fun ();
BB. Fun ();
Console. writeline ( " ~~~~~~~~~~~~~~~~~~ ' " );
A AB = New B ();
A ABB = New BB ();
AB. Fun (); // B. Fun () B use override
ABB. Fun (); // A. Fun () bb use new
Console. writeline ( " A AB = new B (); AB's type is {0} " , AB. GetType (). tostring ());
If (AB Is A)
Console. writeline ( " But AB is also " );
Console. readkey ();
}
}
ClassA
{
Public Virtual VoidFun ()
{
Console. writeline ("A. Fun ()");
}
}
class B: A
{< br> Public override void fun ()
{< br> console. writeline ( " B. fun () using 'override' " );
}< BR >}
ClassBB:
{
Public New VoidFun ()
{
Console. writeline ("BB. Fun () using 'new'");
}
}
The execution result is as follows:
A. Fun ()
B. Fun () using 'override'
BB. Fun () using 'new'
~~~~~~~~~~~~~~~~~~ '
B. Fun () using 'override'
A. Fun ()
A AB = new B (); AB's type is B
But AB is also
Well, let's analyze it.
The first part of the code is "~~~~~~~~~". Above, there should be nothing to say.
The key is to declare "A AB = new B ();". If override is used to override the virtual function method of the parent class in the subclass, the method in the subclass is executed. If the new method is used in the subclass to override the parent class method, the parent class method is executed.
Here, we can understand that override is like an eraser. When it appears, it directly erased the parent class method and put its own on it.
If we use new in the subclass, let's say that there is no eraser, and who should be.