C # difference between new and override

Source: Internet
Author: User

Override refers to "overwrite", which refers to the method that the subclass overrides the parent class. The subclass object cannot access this method in the parent class. New refers to "hiding", which means that the subclass hides the parent class method. Of course, through certain conversions, you can access the parent class method in the subclass object. Therefore, the difference between C # new and override is overwrite and hide.

The following code is used:

Copy codeThe Code is as follows:
<PRE class = csharp name = "code"> 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 overwrites the method of the parent class, the F1 method of the subclass is called here. It is also the embodiment of polymorphism in OO
B1.F1 ();
// Because the new method of the parent class is hidden in the subclass, the hidden parent class method is called.
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.