A special method that runs automatically when an instance is created ** You can freely control the initial state of the instance! ** **
That said, let's actually execute the code.
** Default for each type is entered in the value ** For example, suppose you have a program that retrieves customer information.
//Define customer information
class CustomerCard {
int id; //Customer id
String name; //Customer name
}
class CustomerManager {
public static void main(String[] args) {
CustomerCard out = new CustomerCard(); //Instance creation
System.out.println(out.id); //Output customer id
System.out.println(out.name); //Output customer name
}
}
When I do this, the result is:
0 //Customer id
null //Customer name
When a class is instantiated (new), member variables that do not contain any value are automatically initialized. Remember that there is a rule that numeric types such as int are initialized to 0, boolean types are initialized to false, and reference types such as String are initialized to null.
Let's put the constructor in the previous program, set the ** initial state **, and execute it.
class CustomerCard {
int id; //Customer id
String name; //Customer name
//**Set the initial value in the constructor**
CustomerCard() {
this.id = 1111;
this.name = "taylor";
}
}
class CustomerManager {
public static void main(String[] args) {
CustomerCard out = new CustomerCard(); //Instance creation
System.out.println(out.id); //Output customer id
System.out.println(out.name); //Output customer name
}
}
The result is this.
1111 //Customer id
taylor //Customer name
Yeah, the value specified in the constructor is the initial value. It would be nice to understand roughly that the constructor can set the initial value of the instance like this.
Recommended Posts