[C # tips] C # some confusing concepts (v) --------- in-depth analysis of C # inheritance

Source: Internet
Author: User

Directory:

C # tips] C # some confusing concepts-------- Data type storage location, method call, use of out and ref Parameters

C # tips] C # some confusing concepts 2) -------- constructor, this keyword, partial classification, enumeration C # tips C # some confusing concepts 3) -------- structure, GC collection, static members, static Class C # tips] some confusing concepts in C # (4) --------- parse Console. writeLine ()

---------------------------------- Split line --------------------------------------

The main content of this article is about inheritance.

First, let's take a look at inheritance;

Since there is inheritance, there must be a parent class and a subclass. Let's look at the following code:

Class Person {private int nAge; protected string strName; double douHeight; public string strEateType; public void Hello () {Console. WriteLine ("I can say Hello! ");} Public void Run () {Console. WriteLine (" I can Run! ") ;}} Class Student: Person {}

Then I instantiate the subclass object in the Main) function. The Code is as follows:

Staticvoid Main (string [] args)

{

Student stu1 = new Student ();

}

So what happens in the memory in this process?

Let's take a look at misl's intermediate code and see what we can find.


650) this. width = 650; "src =" http://www.bkjia.com/uploads/allimg/140207/22355352D-0.png "style =" border: 0px; width: 920px; "alt =" 06145810944696.png"/>

From this we can find that the subclass inherits all the members of the parent class, including Private and Protect, and opens up space for these Members to store.

Let's instantiate our subclass and access the fields and methods of the parent class. We will find the following phenomena:

650) this. width = 650; "src =" http://www.bkjia.com/uploads/allimg/140207/2235532P1-1.png "style =" border: 0px; "alt =" 061505509659962.png"/>

Therefore, although the subclass opens up space for all the members of the parent class in the heap, the Private member and protected member protected cannot be accessed.

So in the memory, such:

650) this. width = 650; "src =" http://www.bkjia.com/uploads/allimg/140207/22355341W-2.png "style =" border: 0px; "alt =" 061525055993918.png"/>

Let's look at the following code to explore the members of the class accessed by the this keyword and the base keyword in the subclass. The Code is as follows:

Class Student: Person {private string strClass; private string strAddress; public void Address (string linoleic, string adre) {// here, the this keyword calls the member of the subclass and the non-seemingly Member of the parent class this. strClass = "5"; this. strAddress = "Beijing"; this. strName = "Zi Qiang"; // here, the base keyword is called as a non-seemingly member base of the parent class. strName = "Hadron"; Console. writeLine ("I am {0} age, from {1}", linoleic, adre);} public void Sing () {this. strClass = ""; Console. writeLine ("I can sing! ");}}

Therefore, the access range of the this keyword and the base keyword in the subclass is as follows:

650) this. width = 650; "src =" http://www.bkjia.com/uploads/allimg/140207/2235533I3-3.png "style =" border: 0px; "alt =" 061715362894801.png"/>

Ii. execution sequence of constructor and parent constructor of subclass objects

We add an explicit constructor for the parent class and subclass respectively. The Code is as follows:

Class Person {private int nAge; protected string strName; double douHeight; public string strEateType; // constructor of the parent class public Person () {Console. writeLine ("I am the constructor of the parent class");} public void Hello () {Console. writeLine ("I can say Hello! ");} Public void Run () {Console. WriteLine (" I can Run! ") ;}} Class Student: Person {private string strClass; private string strAddress; // constructor of the subclass public Student () {Console. writeLine ("I Am a subclass constructor ");}}

We use VS's single-step debugging to see the execution sequence of the parent class and sub-class explicitly constructor, such as dynamic images, you can see the process ):

650) this. width = 650; "src =" http://www.bkjia.com/uploads/allimg/140207/22355331M-4.gif "style =" border: 0px; "alt =" 061724588334412.gif"/>

It is easy to find that when a subclass object is created

① The constructor of the subclass is called first.

② The constructor of the parent class is called.

③ Execute the constructor of the parent class

④ Executed the constructor of the subclass.


So why?

I tried to look at the source code through decompilation to explain this reason, but the results of decompilation are as follows,

650) this. width = 650; "src =" http://www.bkjia.com/uploads/allimg/140207/22355332N-5.png "style =" border: 0px; "alt =" 061801203361346.png"/>

Nothing special can be found to explain this reason.


Finally, check Microsoft's official MSDN documentation and find the original answer. Click here)

650) this. width = 650; "src =" http://www.bkjia.com/uploads/allimg/140207/2235535C5-6.png "style =" border: 0px; width: 920px; "alt =" 061801068235143.png"/>

According to the official code example of Microsoft, the following code has the same effect.

// The constructor public Student () {Console. writeLine ("I Am a subclass of the constructor");} // The code here has the same effect as the above Code: public Student (): base () {Console. writeLine ("I Am a subclass constructor ");}

That is to say, as long as the non-argument constructor is explicitly declared in the subclass, if the object of the instantiated subclass is, the non-argument constructor of the subclass will call the constructor without parameters in the parent class.

If the parent class does not have this non-argument constructor, an error is returned.

The following code:

Class Person {private int nAge; protected string strName; double douHeight; public string strEateType; // constructor of the parent class // public Person () // {/Console. writeLine ("I am the constructor of the parent class"); // The constructor with parameters for the parent class. The constructor without parameters is public Person (string str) {Console. writeLine ("I am the constructor of the parent class {0}", str);} public void Hello () {Console. writeLine ("I can say Hello! ");} Public void Run () {Console. WriteLine (" I can Run! ") ;}} Class Student: Person {private string strClass; private string strAddress; // public Student () {Console. writeLine ("I Am a subclass constructor");} public Student (string strName) {Console. writeLine ("My name is {0}", strName );}}


At this time, an error will be reported during compilation,

650) this. width = 650; "src =" http://www.bkjia.com/uploads/allimg/140207/2235531637-7.png "style =" border: 0px; "alt =" 061816031046317.png"/>

Because the constructor with parameters in the parent class overwrites the non-parameter constructor, therefore, the non-parameter constructor of the subclass cannot call back the non-parameter constructor of the parent class to initialize the member variables of the parent class. So an error is reported.

So why should I call the constructor of the parent class when initializing the subclass?

Before initializing a subclass, you must use the constructor to initialize the member variables of the parent class.

What is the significance of executing the constructor of the parent class before the constructor of the Child class?

Assign different default values to non-private member variables of the parent class in the constructor of the parent class and the constructor of the Child class. When instantiating a subclass, The subclass calls the constructor to initialize the member variable. If the constructor of the subclass is executed first, the constructor of the parent class is executed, the value of the parent class member field overwrites the value of the Child class member field. But what we want is the property value of the subclass. To resolve data conflicts, the constructor of the parent class must be executed before the constructor of the Child class.

The following code:

Class Person {private int nAge; private string strName; double douHeight; public string strEateType; // constructor of the parent class public Person () {// then assign the initial value this to strEateType in the parent class. strEateType = "dinner"; Console. writeLine ("I am the constructor of the parent class {0}", strEateType) ;}} class Student: Person {private string strClass; private string strAddress; // The subclass constructor public Student () {// assign the initial value this to the strEateType In the subclass. strEateType = "noodles"; Console. writeLine ("I Am a subclass of the constructor {0}", strEateType );}}

At this time, we declare the value of accessing strEateType through the subclass object, as follows:

Student stu1 = new Student();            //stu1.            string str = stu1.strEateType.ToString();            Console.WriteLine(str);            Console.ReadKey();

The value of the strEateType attribute of the subclass must be printed. If the subclass constructor is executed to assign a value to the strEateType class, the assignment of the constructor of the parent class overwrites the initial value of the strEateType class. The printed value is the value of the parent class member field.Therefore, the constructor of the parent class is executed before the constructor of the Child class.

The output is as follows:

650) this. width = 650; "src =" http://www.bkjia.com/uploads/allimg/140207/2235536262-8.png "style =" border: 0px; "alt =" 061910383266926.png"/>


3. Can the subclass have the same name as the parent class?

The following Code declares a parent class Person:


Class Person {private int nAge; private string strName; double douHeight; public string strEateType; public readonly string strrrr; // constructor of the parent class public Person () {this. strEateType = "dinner"; Console. writeLine ("I am the constructor of the parent class {0}", strEateType);} public Person (string str) {this. strName = str; Console. writeLine ("I am the constructor of the parent class {0}", str);} public void Hello () {Console. writeLine ("I can say Hello to the earth! ");} Public void Run () {Console. WriteLine (" I can Run! ");}}


Declare a subclass to inherit from Person. The Code is as follows:

Class Worker: Person {public void Hello () {Console. WriteLine ("I am a Worker and will say Hello! ");} Public new void Run () {Console. WriteLine (" I am a worker and I will Run! ");}}


Then instantiate the Worker object and print the Hello method. The result is as follows:

650) this. width = 650; "src =" http://www.bkjia.com/uploads/allimg/140207/223553FN-9.png "style =" border: 0px; "alt =" 062124112658094.png"/>


Why? The compiler has already told us, for example:

650) this. width = 650; "src =" http://www.bkjia.com/uploads/allimg/140207/2235534U6-10.png "style =" border: 0px; "alt =" 062126425532539.png"/>


The subclass method hides the parent class method.

Since child classes can define methods with the same name as parent classes, can fields with the same name be defined? The answer is yes, and like the method of the same name, fields with the same name in the subclass will hide fields with the same name in the parent class.

If you think it is good, click like in the lower right corner! Your support is the motivation of my writing!

Graduation internship exchange group: 221376964. You can also pay attention to my Sina Weibo.

650) this. width = 650; "border =" 0 "src =" http://www.bkjia.com/uploads/allimg/140207/2235535439-11.png "style =" border: 0px; "alt =" 1.png"/>


This article is from the blog of "Hadar column", please be sure to keep this source http://yisuowushinian.blog.51cto.com/4241271/1356975

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.