Three methods for initializing data domains in java

Source: Internet
Author: User

Three methods for initializing data domains in java
Three methods for initializing data domains in java:
1. Set the value in the constructor
2. assign values in the Declaration
3. initialize the block (initialization block). A class declaration can contain multiple code blocks,
As long as the class object is constructed, these blocks will be executed, for example:
Class Employee {
Public Employee (String name, double salary ){
This. name = name;
This. salary = salary;
}
Public Employ (){
Name = "";
Salary = 0;
}
...
Private static int nextId;
Private int id;
Private String name;
Private double salary;
...

// Obejct initialization block
{
Id = nextId;
NextId ++;
}
}
// Simple analysis:
In this example, no matter which constructor is used to construct the object, the id domain is initialized in the object initialization block. First, run the initialization block,
Then, in the main part of the running Structure


// Call the constructor's specific processing steps:


(1) All data domains are initialized as default values (0, null)
(2) execute the domain initialization statement and the initialization block in sequence according to the sequence in which the class declaration appears.
(3) If the constructor calls the second constructor In the first line, the second constructor is executed.
(4) The subject that executes this Constructor


// Function code: Assign the start value of the employee ID to a random integer smaller than 10000
// Static initialization block
Static {
Random generator = new Random ();
NextId = generator. nextInt (10000 );
}
When the class is loaded for the first time, the static domain will be initialized, just like the instance domain, unless they are set to other values,
Otherwise, the default initial values are 0, null, and false. All static initialization statements and static initialization blocks are executed in the sequence defined by the class.



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.