C # New and override Difference Analysis _ practical Tips

Source: Internet
Author: User

Override refers to "overwrite", which means that subclasses override the parent class. The method in the parent class can no longer be accessed by the object of the subclass. New is "hidden", which means that subclasses hide the method of the parent class, and of course, through certain transformations, you can access the method of the parent class in the object of the subclass. So the difference between C # new and override is that it covers and hides

Here's the code:

Copy Code code as follows:

<pre class=csharp name= "code" >class Base
{
public virtual void F1 ()
{
Console.WriteLine ("Base ' 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 subclasses override the method of the parent class, the F1 method of the subclass is called here. It's also a manifestation of polymorphism in OO.
B1. F1 ();
Because the method of the parent class is hidden in the subclass with new, the hidden parent class method is called here
B1. F2 ();
}
}

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.