java静态成员变量不需要赋初值

在Employer类中定义了静态成员变量nextID与成员变量ID

class Employer{
    private static int nextID;
    
    private String name;
    private double salary;
    private LocalDate hireDay;
    private int ID=0;
       ......
此时nextID并没有赋初值,而ID初值等于0。下面在Employer类中定义了一个将nextID赋给ID的方法:

public void setID()
    {
        ID = nextID;
        nextID++;
    }
在main函数里面打印出三个Employer对象的ID:

public static void main(String[] args)
    {
    Employer[] staff = new Employer[3];
    staff[0] = new Employer("jack",3000,1987,5,15);
    staff[1] = new Employer("bob",4000,1998,2,20);
    staff[2] = new Employer("Tom",5000,1983,4,18);
    
    for(Employer s :staff) {
        System.out.println("nextID:"+s.getnextID());
        s.setID();
        System.out.println("name="+s.getName()+",salary="+s.getSalary()+",hireDay="+s.gethireDay()+",ID="+s.getID());
    }
    }
结果为

可知,定义静态成员变量不需要赋初值,初值为0

猜你喜欢

转载自blog.csdn.net/fun_always/article/details/79139246