[Java Learning Basics] Java Constructors

Source: Internet
Author: User

A constructor method is a special method in a class that initializes an instance variable of the class, which is automatically called after the object is created (the new operator).

The Java construction method is characterized by the following:

    1. The constructor method name must be the same as the class name.

    2. The constructor method does not have any return values, including void.

    3. The construction method can only be used in conjunction with the new operator.

The sample code is as follows:

1 //Rectangle.java File2  Packagecom.a51work6;3 4 //Rectangle Class5  Public classRectangle {6 7     //Rectangle Width8     intwidth;9     //Rectangle HeightTen     intheight; One     //Rectangular Area A     intArea ; -  -     //Construction Method the      PublicRectangle (intWinth) { -width =W; -Height =h; -Area =Getarea (W, h); +     } -     ... +}

Line 15th of the code declares a construction method with two parameters W and H, used to initialize the width and height of the two member variables of the rectangle object, noting that there are no previous return values.

Default constructor method

Sometimes there is no construction method at all in the class. For example, the user class code in this section is as follows:

1 //User.java File2  Packagecom.a51work6;3 4  Public classUser {5 6     //User name7     PrivateString username;8 9     //User PasswordTen     PrivateString password; One  A}

From the user class code above, there are only two member variables, there is no construction method, but you can call the parameterless construction method to create the user object, because the Java virtual opportunity is not a constructor method of the class, the default constructor method its method body without any statements, The default construction method is equivalent to the following code:

// default constructor Method  Public User () {}

The default constructor method has no statements in the body and cannot initialize member variables, so the member variables use default values, and the member variable defaults are related to the data type.

Constructing method overloads

There can be more than one constructor in a class, they have the same name (same as the class name), and the argument list is different, so they must be overloaded.

The constructor method overloads sample code is as follows:

1 //Person.java File2  Packagecom.a51work6;3 4 Importjava.util.Date;5 6  Public classPerson {7 8     //name9     PrivateString name;Ten     //Age One     Private intAge ; A     //Date of birth -     PrivateDate birthDate; -  the      PublicPerson (String N,intA, Date D) {         -Name =N; -Age =A; -BirthDate =D; +     } -  +      PublicPerson (String N,inta) { AName =N; atAge =A; -     } -  -      PublicPerson (String N, Date d) { -Name =N; -Age = 30; inBirthDate =D; -     } to  +      PublicPerson (String N) { -Name =N; theAge = 30; *     } $ Panax Notoginseng      PublicString GetInfo () { -StringBuilder SB =NewStringBuilder (); theSb.append ("Name:"). Append (name). append (' \ n ')); +Sb.append ("Age:"). Append (Ages). Append (' \ n '); ASb.append ("Date of Birth:"). Append (BirthDate). append (' \ n '); the         returnsb.tostring (); +     } -}

The Code Person class Code provides 4 overloaded construction methods, and if you have accurate name, age, and date of birth information, you can use the construction method of line 15th of the code to create the person object, and if only the name and age information, you can use the Code line 21st construction method to create a person object If only the name and birth date information can be used to create a person object using the construction method of line 26th of the code, if only the name information can be constructed using line 32nd of the code to create the person object.

Tips: If you add a constructor with a parameter to a class, the system does not automatically generate a parameterless constructor, so after adding a constructor with parameters, you can manually add a default parameterless constructor.

Construction Method Encapsulation

The construction method can also be encapsulated, and the access level is the same as the normal method, and the access level of the construction method is referenced in Java Learning Basics, and the encapsulation and access control of the JavaScript is shown in the diagram. The sample code is as follows:

1 //Person.java File2  Packagecom.a51work6;3 4 Importjava.util.Date;5 6  Public classPerson {7 8     //name9     PrivateString name;Ten     //Age One     Private intAge ; A     //Date of birth -     PrivateDate birthDate; -  the     //Public-level restrictions -      PublicPerson (String N,intA, Date D) {         -Name =N; -Age =A; +BirthDate =D; -     } +  A     //Default Level Limit atPerson (String N,inta) { -Name =N; -Age =A; -     } -  -     //Protection level limits in     protectedPerson (String N, Date d) { -Name =N; toAge = 30; +BirthDate =D; -     } the  *     //Private Level Restrictions $     PrivatePerson (String N) {Panax NotoginsengName =N; -Age = 30; the     } +  A     ... the}

The 16th line of the preceding code is the construction method that declares the public level. Line 23rd of the code declares the default level, and the default level can only be accessed in the same package. Line 29th of the code is the construction method of the protection level, which is the same as the default level in the same package and can be inherited by the quilt class in different packages. Line 36th of the code is a private-level construction method that can only be used in the current class and not allowed outside access, and private construction methods may be applied to designs such as singleton design patterns.

----------------------------------------------------------------------------

Initialize the execution order of blocks and constructors

Readers can first read the following code to determine the output:

1   classBextendsObject2   {3       Static4       {5System.out.println ("Load B"); 6       }7        PublicB ()8       {9System.out.println ("Create B"); Ten      } One  }     A  classAextendsB -  { -      Static the      { -System.out.println ("Load A"); -      } -       PublicA () +      { -System.out.println ("Create A"); +      } A  } at   -   Public classTestClass -  { -       Public Static voidmain (String [] args) -      { -          NewA (); in      } -}

Output Result:

Load bload acreate bcreate A

The initialization block executes before the constructor executes, the class initialization stage executes the static initialization block of the topmost parent class, executes down in turn, executes the static initialization block of the current class, and, when the object is created, calls the constructor of the top-level parent class, executes down, and finally calls the constructor of this class. So the order of execution is: parent class static code, subclass static code block, parent class construction code block, parent class constructor, subclass constructor, sub -class constructor

[Java Learning Basics] Java Constructors

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.