Differences between override and new in inheritance classes

Source: Internet
Author: User
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.

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.