Two interview questions about new and override

Source: Internet
Author: User

The meanings of these two keywords are easy to understand, but you may not be able to quickly write the correct answers to the following questions. If you do not believe them, try again.
1. Differences between new and override

View Code
Public abstract class
{
Public ()
{
Console. writeline ('A ');
}
Public Virtual void fun ()
{
Console. writeline ("A. Fun ()");
}
}
Public Class B:
{
Public B ()
{
Console. writeline ('B ');
}
Public new void fun ()
{
Console. writeline ("B. Fun ()");
}
Public static void main ()
{
A A = new B ();
A. Fun ();
Console. Read ();
}
}

What is the output of this code?
Basic principle: override is used to override the base class method, and new is used to hide the derived class of the base class.
There is no difference if you use the type to call its own method
For example

A A = new A (); A. Fun ();
B = new B (); B. Fun ();

Such a call is the same as calling a common member method, and the result is the output of their own method.
If you call a method by referencing the base class, the difference between new and override will come out.
Override can find the method defined in the True Type of the object, while new is just to find the method in the type definition.
The result is as follows:

 

2 virtual and override
The Code is as follows:
Public Class
{
Public Virtual void fun1 (int I)
{
Console. writeline (I );
}
Public void fun2 ()
{
A. fun1 (1 );
Fun1 (5 );
}
}
Public Class B:
{
Public override void fun1 (int I)
{
Base. fun1 (I + 1 );
}
Public static void main ()
{
B = new B ();
A A = new ();
A. fun2 (B );
B. fun2 ();
}
}
This code is also very strange, and the head is dizzy.
The result is as follows:

Sometimes writeProgramIt takes a lot of effort to carefully view the results.

You will be dizzy if you have the following questions:
Call time of type Initiators

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.