判断类对象的个数
package 类的静态字段;
public class 统计对象个数 {
static class Employee
{
static int num;
public Employee(){
num = num + 1;
}
int sum1() {
return num;
}
}
static class Employee
{
static int num;
public Employee(){
num = num + 1;
}
int sum1() {
return num;
}
}
public static void main(String []args) {
Employee A = new Employee();
Employee B = new Employee();
Employee C = new Employee();
Employee D = new Employee();
Employee E = new Employee();
Employee F = new Employee();
System.out.println("你已创建"+Employee.num+"个对象");
}
}
![](https://img2018.cnblogs.com/blog/1279396/201810/1279396-20181021183322589-1242796973.png)
因为在类的构造函数被修改之后,初始化对象只调用修改后的函数,所以对象未被初始化,应该加上函数的参数,这样对象才会被初始化。
静态初始化块的执行顺序:
静态初始化块最优先被执行,而且只能够执行一次。构造函数在其之后执行,而且没生成一次对象就调用构造函数一次。
非静态初始化块构造函数之前被执行。构造函数就是将对象初始化。