Java object constructs

Source: Internet
Author: User

Some understanding of object construction.

Default Domain Initialization

If the domain is given an initial value in the constructor, it is automatically assigned the default: The value is 0, the Boolean value is False, and the object reference is null. However, this is obviously unsafe, and invoking a method on a null reference is not expected.

class employee{    private  String name;     Private Double salary; }

No parameter constructor

Each class contains a parameterless constructor whose state is set to the appropriate default value when the object is created by a parameterless constructor. If the program does not write a constructor, the constructor sets all instance fields to the default values: 0, the Boolean value is False, and the object reference is null.

if at least one constructor is provided in the class, but no parameterless constructor is provided, then no parameters are considered illegal when constructing the object. that is , the system provides a default constructor only if the class does not provide any constructors.

class employee{    private  String name;     Private Double salary;      Public Employee () { //=        The default constructor provided by the system is  null;         this. Salary = 0;       }}

Display domain initialization

It is a good design practice to set the initial state of the instance domain of the class displayed to ensure that each instance field can be set to a meaningful value, regardless of the call to any constructor .

class employee{    private String name= "Zhang San";     Private double salary=30000;      Public Employee () {  this. Name = ' Zhang San ';  this. Salary = "30000"                     }  

Constructor method overloading

If multiple methods have the same name, different parameters, the overloads are generated. The constructor method also supports overloading. The compiler executes the corresponding method by matching the type of the parameter given by each method with the value used by the particular method invocation. If there is no match, a compilation error is generated.

classemployee{PrivateString name; Private Doublesalary;  PublicEmployee () { //constructor one        This. Name = "Zhang San"; This. Salary = "30000"} PublicEmployee (string name) { //constructor two            This. Name =name;  This. Salary = "20000"; }   }

Call another constructor

If the first statement of the constructor is shaped like this (...), the constructor calls another constructor of the same class.

classemployee{PrivateString name; Private Doublesalary;  PublicEmployee (Doublesalary) { //constructor one  This("John Doe", salary);    //Will call constructor two }  PublicEmployee (String name,Doublesalary) { //constructor two  This. Name =name;  This. Salary = "20000"; }   }

Initializing blocks and initialization statements

In a declaration of a class, you can include multiple blocks of code that are executed as long as the object is constructed.

class employee{    private String name= "John Doe";    // Initialize Statement    Private Double   salary; {  // initialize block        salary = "10000";       }      Public Employee () {        this. Name = ' Zhang San ';    this. Salary = "30000"                       }}  

to invoke the constructor, proceed as follows:

1) All data fields are initialized to default values

2) Execute all domain initialization statements and initialization blocks sequentially, in the order in which they appear in the class declaration.

3) If the first row of the called constructor calls another constructor, the constructor principal is executed.

4) Execute this constructor body.

Instance:

1 ImportJava.util.Random;2 3 4  Public classconstructortest{5      Public Static voidMain (string[] args) {6employee[] Staff =NewEmployee[3];7 8Staff[0] =NewEmployee ("Harry", 40000);//Call Constructor One9System.out.println ("name=" + staff[0].getname () + ", id=" + staff[0].getid () + ", salary=" + staff[0].getsalary ());TenSTAFF[1] =NewEmployee (60000);//calling the constructor two OneSystem.out.println ("name=" + staff[1].getname () + ", id=" + staff[1].getid () + ", salary=" + staff[1].getsalary ()); ASTAFF[2] =NewEmployee ();//Call Constructor Three, which is the same as the default constructor of the system when the constructor is not provided -System.out.println ("name=" + staff[2].getname () + ", id=" + staff[2].getid () + ", salary=" + staff[2].getsalary ()); -     } the } -  -  - classEmployee { +     Private Static intNextID; -     Private intID; +     PrivateString name= "";//Initialize Statement A     Private Doublesalary; at  -     Static{//Static initialization blocks -System.out.println ("Static block initialization"); -Random generator =NewRandom (); -NextID = Generator.nextint (10000); -     } in{//Initialize block -SYSTEM.OUT.PRINTLN ("Normal initialization block"); toID =NextID; +nextid++; -     } the  *      PublicEmployee (String name,DoubleSalary) {//Constructor One $          This. Name =name;Panax Notoginseng          This. Salary =salary; -     } the  +      PublicEmployee (DoubleSalary) {//Constructor Two A          This("Emploee #" +NextID, salary); the     } +  -      PublicEmployee () {//Constructor Three $  $     } -  -      PublicString GetName () { the         returnname; -     }Wuyi  the      Public Doublegetsalary () { -         returnsalary; Wu     } -  About      Public intgetId () { $         returnID; -     } -}

Operation Result:

Static block initialization
Normal initialization block
name=harry,id=5376,salary=40000.0
Normal initialization block
Name=emploee #5377, id=5377,salary=60000.0
Normal initialization block
name=,id=5378,salary=0.0

Static blocks run only once because static blocks run when the class loads, rather than when the object is created. The entire lifetime value of the program is also run only once. See the Java class loading process for details.

Java object constructs

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.