Appearance
Constructor
When creating an instance, we often need to initialize the fields of the instance at the same time, for example:
java
Person p = new Person();
p.setName("bob");
p.setAge(12);
Initializing an object instance requires 3 lines of code, and if you forget to call setName()
or setAge()
, the internal state of the instance will be incorrect.
Can all internal fields be initialized to appropriate values when creating an object instance?
Absolutely.
At this time, we need the constructor method.
When creating an instance, the instance is actually initialized through the constructor method. Let's first define a constructor that can pass in name
and age
at once when creating Person
instance to complete the initialization:
java
public class Main {
public static void main(String[] args) {
Person p = new Person("Bob", 15);
System.out.println(p.getName());
System.out.println(p.getAge());
}
}
class Person {
private String name;
private int age;
public Person(String name, int age) {
this.name = name;
this.age = age;
}
public String getName() {
return this.name;
}
public int getAge() {
return this.age;
}
}
Because constructors are so special, the name of the constructor is the class name. There are no restrictions on the parameters of the constructor, and any statement can be written inside the method. However, compared with ordinary methods, constructors have no return value (and no void
). To call a constructor, you must use new
operator.
Default Constructor
Does any class
have a constructor? Yes.
We didn't write a constructor for the Person
class earlier, so why can we call new Person()
?
The reason is that if a class does not define a constructor, the compiler will automatically generate a default constructor for us, which has no parameters and no execution statements, similar to this:
java
class Person {
public Person() {
}
}
It is important to note that if we customize a constructor, the compiler will no longer automatically create a default constructor:
java
public class Main {
public static void main(String[] args) {
Person p = new Person(); // Compilation error: This constructor cannot be found
}
}
class Person {
private String name;
private int age;
public Person(String name, int age) {
this.name = name;
this.age = age;
}
public String getName() {
return this.name;
}
public int getAge() {
return this.age;
}
}
If you want to be able to use the constructor with parameters and retain the constructor without parameters, you can only define both constructors:
java
public class Main {
public static void main(String[] args) {
Person p1 = new Person("bob", 15); // You can also call the constructor with parameters
Person p2 = new Person(); // You can also call the parameterless constructor
}
}
class Person {
private String name;
private int age;
public Person() {
}
public Person(String name, int age) {
this.name = name;
this.age = age;
}
public String getName() {
return this.name;
}
public int getAge() {
return this.age;
}
}
When a field is not initialized in the constructor, the reference type field defaults to null
, the numeric type field uses the default value, the int
type default value is 0
, and the Boolean type default value is false
:
java
class Person {
private String name; // Default initialized to null
private int age; // Default initialized to 0
public Person() {
}
}
Fields can also be initialized directly:
java
class Person {
private String name = "Unamed";
private int age = 10;
}
Then the question comes: initialize the fields and initialize the fields in the constructor:
java
class Person {
private String name = "Unamed";
private int age = 10;
public Person(String name, int age) {
this.name = name;
this.age = age;
}
}
When we create an object, what is the initial value of the field in the object instance obtained by new Person("bob", 12)
?
In Java, when creating an object instance, initialize it in the following order:
- Initialize the field first, for example,
int age = 10
; means the field is initialized to10
,double salary
; means the field is initialized to0
by default,String s
; means the reference type field is initialized tonull
by default; - Execute the code of the constructor method for initialization.
Therefore, the code of the constructor is run later, so the field value of new Person("bob", 12)
is ultimately determined by the code of the constructor.
Multiple Constructors
Multiple constructors can be defined. When called through the new
operator, the compiler automatically distinguishes them through the number, position and type of parameters of the constructor:
java
class Person {
private String name;
private int age;
public Person(String name, int age) {
this.name = name;
this.age = age;
}
public Person(String name) {
this.name = name;
this.age = 12;
}
public Person() {
}
}
If you call new Person("bob", 20);
it will automatically match the constructor public Person(String, int)
.
If you call new Person("bob");
the constructor public Person(String)
will be automatically matched.
If new Person();
is called, the constructor public Person()
will be automatically matched.
A constructor can call other constructors to facilitate code reuse. The syntax for calling other constructors is this(…)
:
java
class Person {
private String name;
private int age;
public Person(String name, int age) {
this.name = name;
this.age = age;
}
public Person(String name) {
this(name, 18); // Call another constructor Person(String, int)
}
public Person() {
this("Unnamed"); // Call another constructor Person(String)
}
}
Practise
Please add a (String, int)
constructor to the Person
class:
java
public class Main {
public static void main(String[] args) {
// TODO: Add a constructor method to Person:
Person ming = new Person("bob", 12);
System.out.println(ming.getName());
System.out.println(ming.getAge());
}
}
class Person {
private String name;
private int age;
public String getName() {
return name;
}
public int getAge() {
return age;
}
}
Summary
When an instance is created, its corresponding constructor is called through the new
operator, and the constructor is used to initialize the instance;
When no constructor is defined, the compiler will automatically create a default parameterless constructor;
Multiple construction methods can be defined, and the compiler automatically determines based on the parameters;
You can call another constructor within a constructor to facilitate code reuse.