import java.util.*;
/*
类加载顺序:首先执行静态字段和静态代码块,然后执行实例字段和普通代码块,然后执行构造函数。
*/
public class Sample
{
public static void main(String[] args)
{
Employee[] staff = new Employee[3];
staff[0] = new Employee("Harry",40000);
staff[1] = new Employee(60000);
staff[2] = new Employee();
for(Employee item : staff)
{
System.out.println("name="+item.getName()+",id="+item.getId()+",salary="+item.getSalary());
}
}
}
class Employee
{
public Employee(String n,double s)
{
this.name = n;
this.salary = s;
}
public Employee(double s)
{
this("Employee #"+nextId,s);//必须是第一行,否则编译错误,不能与super一起。
}
public Employee()
{
//如果一个类没有自己定义构造函数,那么系统就会自己的提供一个默认的构造函数。
}
public String getName()
{
return name;
}
public double getSalary()
{
return salary;
}
public int getId()
{
return id;
}
private static int nextId;
private int id;
private String name = "";
private double salary;
{
//代码块
id = nextId;
nextId++;
}
static
{
//静态代码块
Random generator = new Random();
nextId = generator.nextInt(10000);
}
}
重载、初始化块、this、默认构造函数,布布扣,bubuko.com
原文:http://my.oschina.net/Sadhu/blog/293208