static作用:
多个对象共享同一份数据,一旦用了static关键字。那么这样的内容不再属于自己,而是属于类,只在类中保存唯一一份,所有对象共享同一份。
成员变量中static用法
/*
类的定义注意事项:
成员变量是直接定义在类党总的,在方法外边
成员方法不要写static关键字。
*/
public class Student {
private int id;//学号,不在构造方法中使用
private String name;//姓名
private int age;//年龄
static String room;//教室
private static int idCounter = 0; //计数器,自动生成学号使用
public Student() {
this.id = ++idCounter;
}
public Student(String name, int age) {
this.id = ++idCounter;
this.name = name;
this.age = age;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public static String getRoom() {
return room;
}
public static void setRoom(String room) {
Student.room = room;
}
}
//创建实例
public class StaticDemo {
public static void main(String[] args) {
Student stu = new Student("李四",18);
stu.room = "教室001";
Student stu1 = new Student("张三",26);
System.out.println("姓名:" + stu.getName() + "年龄:" + stu.getAge() +
"所在教室:" + stu.room + "学号:" + stu.getId());
System.out.println("姓名:" + stu1.getName() + "年龄:" + stu1.getAge() +
"所在教室:" + stu1.room + "学号:" + stu1.getId());
}
}