Java Basics--builder __java

Source: Internet
Author: User

constructors are a special method that performs initialization when an instance is created. constructors are an important way to create objects (even if you create objects in the form of Factory mode, reflection, and so on, and they depend on the constructor), so the Java class must contain one or more constructors.

First, initialize using constructors
the greatest use of constructors is to perform initialization when an object is created . When an object is created, the system initializes the instance variable of the object by default, which sets the instance variable for all the base types to 0 (for the numeric instance variable) or False (for the Boolean instance variable), and sets the instance variable of all reference types to null.

If you change this default initialization and you want the system to create an object that specifies initialization for the object's instance variable display, you can do so through the constructor.

Note: If the programmer does not provide any constructors for the Java class, the system provides a parameterless constructor for the class, which is empty and does nothing.

Let's look at an example:

public class Constructortest
{public
    String name;
    public int count;
    Provides a custom constructor that contains two parameters public
    constructortest (String name, int count)
    {
        //constructor This represents the object
        that he initializes this.name = name;
        This.count = count;
    }
    public static void Main (string[] args)
    {
        //using a custom constructor to create an object//the
        system will perform a custom initialization on the object
        constructortest TC = new Constructortest ("Java", 1);
        The output Constructortest object's name and count two instance variables
        System.out.println (tc.name);
        System.out.println (Tc,count);
    }

Running the above program, you can see that when the output Constructortest object, its name instance variable is the Java,count instance variable when 0.

Q: The constructor is the way to create an object , not to say that the constructor is entirely responsible for creating Java objects.

Answer: no . The constructor is an important way to create a Java object, which is also returned by the constructor when called by the New keyword, but the object is not created entirely by the constructor. in fact, when the program calls the constructor, the system allocates the memory space for the object and performs the default initialization for the object, which has already been created--these operations are done in the constructor execution Zian . That is, the system has created an object before the system starts executing the constructor , except that the object is not yet accessible by the external system . Can only be referenced in this constructor through this. when the execution of the constructor finishes, the object is returned as the constructor's return value and is usually assigned to another variable of the reference type, so that the external program can access the variable .

Once the programmer provides a custom constructor, the system no longer provides a default constructor . Therefore, the Constructortest class above can no longer create an instance through the new Constructortest () code, because the class no longer contains constructors without parameters.

If you want to keep a constructor without parameters, or if you want to have multiple initialization procedures, you can provide multiple constructors for that class . If more than one constructor is provided in a class, the overload of the constructor is formed.

because the constructor is used primarily by other methods to return instances of the class, the constructor is set to public access, allowing classes anywhere in the system to create objects of that class . Unless, in extreme cases, the business needs to limit the objects that create the class, you can set the constructor to other access rights, such as protected, which is used primarily for invocation by its subclasses.

Second, constructor overload
With multiple constructors in the same class, multiple constructors have different formal parameter lists, which is the overload of the constructor . Constructor overloading allows a Java class to contain multiple initialization logic, allowing the use of different constructors to initialize Java objects.

Constructor overloads and method overloads are basically similar: the constructors are required to have the same name . This need not be specifically required because the constructor must be the same as the class name, so all the constructor names of the same class see the same. In order for the system to differentiate between constructors, the argument lists of multiple constructors must be different.

The following Java class demonstrates a constructor overload that allows you to create a Java object from a different constructor by using constructor overloading.

public class Constructoroverload
{public
    String name;
    public int count;
    Provides constructor public
    Constructoroverload () {} with no parameters//
    provides constructor with two parameters
    //Initialize public to object returned by this constructor
    Constructoroverload (String name,int count)
    {
        this.name = name;
        This.count = count;
    }
    public static void Main (string[] args)
    {
        //Creates a Constructoroverload object through a parameterless constructor
        constructoroverload OCL = New Constructoroverload ();
        Create a Constructoroverload object with a parameter constructor
        constructoroverload oc2 = new Constructoroverload ("Java", 1);
        System.out.println (Oc1.name + "" + oc1.count);
        System.out.println (Oc2.name + "" + Oc2.count);
    }

The above Constructoverload class provides two overloaded constructors, two constructors have the same name, but the parameter list is different, and when the system calls the constructor through new, the system will decide which constructor to invoke based on the list of arguments passed in.

If a system contains more than one constructor, the execution body of one of the constructors fully contains the execution body of the other constructor .
Builder A

Code line one line two code line
Three

Builder B

Code line two code line
three
code line four

As you can see, constructor B completely contains constructor a. For this fully inclusive scenario, if this relationship exists between two methods, you can call method A in method B. However, the constructor cannot be invoked directly, and the calling constructor must invoke the constructor with the new keyword, which causes the system to re-create an object. In order to invoke the initialization code in constructor A in constructor B without recreating a Java object, you can invoke the appropriate constructor using the This keyword.

The following code implements the initialization code that uses another constructor directly in one constructor

public class Apple
{public
    String name;
    public String color;
    public double weight;
    The constructor for public Apple () {}
    //Two parameters is public
    apple (String name,string color)
    {
        this.name = name;
        This.color = color;
    }
    Three-parameter constructor public
    Apple (String name,string color, double weight)
    {
        //calling the initialization code
        of another overloaded constructor through this This (name, color);
        The following this refers to the Java object this.weight = weight that the constructor is initializing
        ;

The Apple class above contains three constructors, where a third constructor invokes the initialization code of another overloaded constructor through this. In the program this (name,color); The call indicates that another constructor with two string parameters is invoked on the class.

use this to invoke another overloaded constructor that can only be used in the constructor and must act as the first statement of the constructor execution body . When an overloaded constructor is invoked using this, the system will invoke the constructor corresponding to the parameter list according to the arguments in this parentheses.

Why use this to invoke another overloaded constructor. I'll just copy and paste the code from another constructor into this constructor.

A: If only from the point of view of the software function, so copy, paste can achieve this effect, but from a software engineering point of view, this is pretty bad. There is a rule in software development not to write the same code more than two times. Because the software is a product that needs to be constantly updated, if one day you need to update the initialization code in constructor A above, assume that constructor B, constructor C ... Contains the same initialization block code, you need to open both the constructor A, constructor B, constructor c ... code to modify it, or, if constructor B, constructor C .... is to invoke constructor A's initialization code through this, you only need to open constructor A to modify it, try to avoid the same code recurrence, make full use of each piece of code, can make the program more concise, also can reduce the software maintenance costs .

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.