1. 构造器的重载
2. 默认构造器
3. 对象初始化块
4. 静态初始化块
5. 实例域初始化
1 public class Employee { 2 3 private String name; 4 5 private double salary; 6 7 private int id = -1; 8 9 private static int nextId = 1; 10 11 { 12 System.out.println("开始对象初始化块。。。"); 13 System.out.println("对象初始化开始前 id:" + id); 14 id = 5; 15 System.out.println("结束对象初始化块"); 16 System.out.println("对象初始化结束 id:" + id); 17 } 18 19 static { 20 System.out.println("开始静态初始化块。。。"); 21 System.out.println("结束静态初始化块"); 22 } 23 public Employee() { 24 System.out.println("无参数的构造方法"); 25 } 26 27 public Employee(String name, double salary) { 28 this(); 29 this.name = name; 30 this.salary = salary; 31 this.id = 0; 32 } 33 34 35 public static void main(String[] args) { 36 Employee.getNextId(); 37 Employee e = new Employee("Harry", 50000); 38 System.out.println(e.getId() + " " +e.getName() + " " + e.getSalary()); 39 } 40 public String getName() { 41 return name; 42 } 43 44 public void setName(String name) { 45 this.name = name; 46 } 47 48 public double getSalary() { 49 return salary; 50 } 51 52 public void setSalary(double salary) { 53 this.salary = salary; 54 } 55 56 public int getId() { 57 return id; 58 } 59 60 public void setId(int id) { 61 this.id = id; 62 nextId++; 63 } 64 65 public static int getNextId() { 66 return nextId; 67 } 68 69 }
执行结果:
开始静态初始化块。。。
结束静态初始化块
开始对象初始化块。。。
对象初始化开始前 id:-1
结束对象初始化块
对象初始化结束 id:5
no paramter con
0 Harry 50000.0