Why use the this constructor and the this constructor?

Source: Internet
Author: User

Why use the this constructor and the this constructor?

When a class has multiple constructors, this constructor is often used:

public class SomeClass
{
    public SomeClass()
    {
// TODO: Initialize some fields
    }
    public SomeClass(string temp) : this()
    {
// TODO: Initialize other fields
    }
}

 

Here, why should we use the this constructor? This should begin with field initialization.

 

Assume that such a class initializes a field when declaring a field. On the client, create an object instance using two constructors of this class.

   class Program
    {
        static void Main(string[] args)
        {
            SomeClass sc = new SomeClass();
            SomeClass sc1 = new SomeClass("jack");
        }
    }
    public class SomeClass
    {
        private int _age = 20;
        private string _name = "darren";
        public SomeClass()
        {
        }
        public SomeClass(string name)
        {
            _name = name;
        }
    }

 

Decompile the code into IL:

It can be seen that the _ age and _ name fields are initialized each time the class constructor is called. Can I put this duplicate part in a public place? The answer is yes. You can submit the field initialization to a non-argument constructor. Modify as follows:

 

   public class SomeClass
    {
        private int _age;
        private string _name;
        public SomeClass()
        {
            _age = 20;
            _name = "darren";
        }
        public SomeClass(string name) : this()
        {
            _name = name;
        }
    }


The preceding Code does not initialize the _ age and _ name fields in the parameter constructor of SomeClass. Instead, it calls the parameter-free constructor of SomeClass, using this constructor avoids repeated initialization fields.


In the constructor, why does this or super need to be placed in the first line?

Suppose we allow this and super to be placed anywhere. Please refer to the following code: class A {A () {System. out. println ("You call super class non-args constructor! ") ;}} Class B extends A {B () {// here, the compiler will automatically add super (); System. out. println (" You call subclass constructor! ");} B (String n) {super (); this (); // actually called B (){...}, in B (){...} the compiler automatically adds // super (); this is equivalent to calling super () twice; that is to say, the parent class is initialized twice. When instantiating an object, a constructor can only be called once. this indicates that this and super cannot exist in a constructor at the same time. At the same time, because the system does not find this () or super () call in the first line, super () is automatically added. If this () and super () are not () in the first line, there will be conflicts. // Because there is always a super () in the second sentence. Therefore, this program cannot be compiled !!! } That is to say, You must place the super or this constructor In the first line of the constructor. Otherwise, the compiler automatically places a super constructor with an empty parameter, other constructors can also call super or this to call a recursive constructor. The final result is the constructor of the parent class (there may be multi-level parent class constructor) it is always executed before the subclass constructor and recursively calls the parent class constructor. The constructor of the current class cannot be executed. In this way, no object can be instantiated, and this class becomes an inaction class. On the other hand, the subclass inherits the attributes and methods of the parent class from the parent class. If the initialization of the members of the parent class is not completed in the subclass, The subclass cannot be used, it should be a member in java that cannot be called without initialization. It is executed sequentially in the constructor, that is, the parent class must be initialized in the first row. Super can directly complete this function. This () can also be done by calling other constructors in This class.

This () must be written in the first line of the constructor! (Because there is no object before the constructor): How should this sentence be understood?

This () super ()
If you want to call another constructor or control the parent class constructor with parameters passed in to the current constructor or data in the constructor, in a constructor, you can only use one of this () or super (), and The called location can only be in the first line of the constructor, in the subclass, if you want to call the constructor of the parent class to initialize the part of the parent class, use the appropriate parameter to call super (). If you use super () without parameters () to call the constructor of the parent class (this () is not used to call other constructor at the same time). The default constructor of the parent class will be called, if the parent class does not have a default constructor, the compiler reports an error.

Why is it in the first row?
Example:
Class {
A (){
System. out. println ("You call super class non-args constructor! ");
}
}
Class B extends {
B (){
// Here, the compiler will automatically add super ();
System. out. println ("You call subclass constructor! ");
}
B (int c ){
System. out. println ("wrong, wrong ");
}
B (String n ){
Null // super ();
System. out. println ("think about it like this ");
This ();
// Actually, B () {...} is called (){...}, B (){...} super (); so super () is called twice, that is, A is initialized twice. When instantiating an object, a constructor can only be called once, which is obviously incorrect.
}

B (double c ){
This ();
This (3 );
// In fact, the super () is called twice, that is, the initialization of A is performed twice, so the result is incorrect.
}
}

Note: any class must have a parent class. If you have not created a parent class for this class, the parent class of this class is Object;

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.