静态域与静态方法(static)
1、静态方法是一种不能向对象实施操作的方法。
2、静态方法的核心是通过类名直接调用,而不用新建对象。
public class EmployeeStaticTest {
/**
*实例域
*/
private static int nextID = 1; //静态域: 1、所有类对象将共享一个nextID。2、即使没有一个对象,静态域也是存在的。
private String name;
private double salary;
private int id;
/**
*构造器
*/
public EmployeeStaticTest(String name, double salary) {
this.name = name;
this.salary = salary;
this.id = 0;
}
/**
* 方法
*/
public String getName() {
return name;
}
public double getSalary() {
return salary;
}
public int getId() {
return id;
}
public void setId() {
id = nextID;
nextID++;
}
public static int getStaticID() {
return nextID; //对于静态域,要使用静态方法对其进行操作。
}
/**
* 主方法
*/
public static void main(String[] args) {
EmployeeStaticTest e = new EmployeeStaticTest("周杰伦", 3000);
//e.setId();
//e.setId();
//e.setId();
System.out.println(EmployeeStaticTest.nextID);//即使没有一个对象,静态域也是存在的。
System.out.println(e.getName() + " " + e.getSalary() + " " + e.getId());
}
}