C # Summary of interview questions

Source: Internet
Author: User


Using System;
Class
{
Public ()
{
PrintFields ();
}
Public virtual void PrintFields (){}
}
Class B:
{
Int x = 1;
Int y;
Public B ()
{
Y =-1;
}
Public override void PrintFields ()
{
Console. WriteLine ("x = {0}, y = {1}", x, y );
}
What is the output when new B () is used to create B's instance?
Answer: X = 1, Y = 0

Answer:
Before constructing B, execute the variable first. y does not explicitly assign values. The default value is 0. Execute the constructor of B. Because B inherits A, execute the constructor of A first. The PrintFields method called by A constructor is A virtual function in Class A, and its implementation is in Class B. Therefore, the PrintFields method of Class B is executed and the result is output. Although the constructor B is executed, the value of y is-1, but the result has been output before.

1-8 represents the execution process of new B.
Class
{
Public A () // ④
{
PrintFields (); // ⑤, found to be overwritten → ⑥
}
Public virtual void PrintFields (){}
}
Class B:
{
Int x = 1; // ①
Int y; // ②
Public B () // ③ it is found that the constructor of A inherits from A and runs the constructor of A immediately.
{
Y =-1; // finished. At this point, the object has been created.
}
Public override void PrintFields () // ⑥
{
Console. WriteLine ("x = {0}, y = {1}", x, y); // 7, output, at this time: x = 1, y = 0
}
}

When the program instantiates B, because of the inheritance relationship, B will first call the constructor of its parent class, And A's constructor calls PrintFields. In A, printFields is A virtual method ,, so it will call rewrite in B. When PrintFields is called, the construction of B is not executed yet, so y = 0 instead of-1. so the output result is x = 1, y = 0 if B B = new B (); B. printFields (); then the output result is x = 1, y =-1

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.