Calling Another Constructor
if the first statement of a constructor has the form this(...)
, then the constructor calls another constructor of the same class. For example,
public Employee(double s)
{
this("Employee #" + nextId, s);
nextId++;
}
When you call `new Employee(60000), the `Employee(double)` constructor calls the `Employee(String, double)` constructor.
import java.util.*;
/*
- This program demonstrates object construction.
*/
public class ConstructorTest
{
public static void main(String[] args)
{
// fill the staff array with three Employee objects
Employee[] staff = new Employee[3];
staff[0] = new Employee("Harry", 40000);
staff[1] = new Employee(60000);
staff[2] = new Employee();
//print out inofrmation about all Employee objects
for(Employee anEmployee : staff)
{
System.out.println("name =" + anEmployee.getName() + ", id =" + anEmployee.getId() + ", salary="
+ anEmployee.getSalary());
}
}
}
class Employee
{
private static int nextId;
private int id;
private String name = ""; //instance field initialization
private double salary;
//static initialization block
{
Random generator = new Random();
// set nextId to a random number between 0 and 9999
nextId = generator.nextInt(10000);
}
// object initialization block
{
id = nextId;
nextId++;
}
// three overload constructors
public Employee(String n, double s)
{
name = n;
salary = s;
System.out.println("Constructor: Employee(String n, double s) is called.");
}
public Employee(double s)
{
// calls the Employee(String, doulbe)constructor
this("Employee #" + nextId, s);
}
// the default constructor
public Employee()
{
// name initialization to "" --see above
// salary not explicitly set -- initialized to 0
// id initialized in initialization block
System.out.println("The default constructor Employee() is called.");
}
public String getName()
{
return name;
}
public double getSalary()
{
return salary;
}
public int getId()
{
return id;
}
}
输出结果:
Constructor: Employee(String n, double s) is called.
Constructor: Employee(String n, double s) is called.
The default constructor Employee() is called.
Disconnected from the target VM, address: '127.0.0.1:36707', transport: 'socket'
name =Harry, id =257, salary=40000.0
name =Employee #258, id =4283, salary=60000.0
name =, id =2113, salary=0.0
Process finished with exit code 0