- override means "overwrite", which means that the subclass overrides the parent class's method. The object of the subclass can no longer access the method in the parent class. (Signature must be the same)
- new means "hidden", which means that the subclass hides the method of the parent class, and of course, the method of the parent class can be accessed in the object of the subclass through certain transformations.
What is the result of running the following code?
[CSharp]View Plaincopyprint?
- Class Base
- {
- public virtual void F1 ()
- {
- Console.WriteLine ("Base s virtual function F1");
- }
- public virtual void F2 ()
- {
- Console.WriteLine ("Base ' s virtual fucntion F2");
- }
- }
- Class Derived:base
- {
- public override void F1 ()
- {
- Console.WriteLine ("Derived ' s override function F1");
- }
- public new void F2 ()
- {
- Console.WriteLine ("Derived ' s new function F2");
- }
- }
- Class Program
- {
- public static void Main (string[] args)
- {
- Base B1 = new Derived ();
- //Because the subclass overrides the method of the parent class, this is called the F1 method of the subclass. is also the embodiment of the multi-state in Oo
- B1. F1 ();
- //Because the method of the parent class is hidden in the subclass with new, so this is called the hidden Parent class method
- B1. F2 ();
- }
- }
or we can use the following code to make it easier to understand:[CSharp]View Plaincopyprint?
- Class Program
- {
- public static void Main (string[] args)
- {
- Derived B1 = new Derived ();
- //Because the subclass overrides the method of the parent class, this is called the F1 method of the subclass. is also the embodiment of the multi-state in Oo
- (Base) B1). F1 ();
- //Because the method of the parent class is hidden in the subclass with new, so this is called the hidden Parent class method
- (Base) B1). F2 ();
- }
- }
The above two outputs are:
Derived ' s override function F1
Base ' s virtual fucntion F2
In the above example, because F1 overrides the original method, the F1 method of the subclass is still called even if the object is turned into the parent class. Because the F2 method of the subclass only "hides" the F2 method of the parent class, the F2 method of the previously hidden parent class is called when the object that is cast to the parent class (Base) calls the F2 method.
The difference between new and override in C #