类与对象-补充:重载构造器,用this(…)调用另一个构造器,无参数构造器,对象初始化块,静态初始化块,实例字段初始化
import java.util.*;
/**
*This program demonstrates object construction.
*@version 1.3 2022-3-14
*@author Xu
*/
public class ConstructorTest
{
public static void main(String[] args)
{
var[] employee = new Employee[3];
employee[0] = new Employee("ExistName",1000);
employee[1] = new Employee(2000);
employee[2] = new Employee();
for(Employee e : employee)
System.out.println(e.getName() + e.getId() + e.getSalary());
}
}
class Employee
{
private static int nextId;
private String name = "";
private double salary;
private int id;
static
{
var generator = new Random();
nextId = generator.nextInt(10000);
}
{
id = nextId;
nextId++;
}
public Employee(String aName, double aSalary)
{
name = aName;
salary = aSalary;
}
public Employee(double aSalary)
{
//this(...)构造器将调用同一个类的另一个构造器
this("Employee#"+nextId,aSalary);
}
public Employee()
{
//如果一个类中提供了至少一个构造器,但是没有提供无参数的构造器,那么构造对象时如果不提供参数是不合法的。
}
public String getName()
{
return name;
}
public double getSalary()
{
return salary;
}
public int getId()
{
return id;
}
}