Java核心技术 卷一 笔记九 类封装及静态

来源:互联网 发布:js 抽奖 可设置几率 编辑:程序博客网 时间:2024/04/28 17:54


public class Employee {


private static int nextId=1;   //静态常量  在这个类中这个值是共有的  但是是私有属性
private String name;
private double salary;
private int id;

public Employee(String n,double s) {              //构造器
// TODO Auto-generated constructor stub
name=n;
salary=s;
id=0;

}


public String getName() {                     //封装
return name;
}


public double getSalary() {
return salary;
}


public int getId() {
return id;
}


public void setId() {
id=nextId;
this.id = id;
}
    
public static int getNextId(){             //静态函数 可以反问自身类的静态域
return nextId;
}

// public static void main(String[] args) {
// Employee e=new Employee("Herry", 5000);
// System.out.println(e.getName()+" "+e.getSalary());
// }

}





public class StaticTest {


public static void main(String[] args) {
Employee [] staff =new Employee[3];

staff[0]=new Employee("Tom",4000);
staff[1]=new Employee("Dick",6000);
staff[2]=new Employee("Harry",6500);

for(Employee e:staff)
{
e.setId();
System.out.println("name="+e.getName()+",id="+e.getId()+"salary="+e.getSalary());
}
// int n=Employee.getNextId();
// System.out.println("next a id="+n);
}
}

0 0