标题144 static关键字静态修饰成员变量
package Demo03;//144 static关键字静态修饰成员变量
public class Student {
private String name;
private int age;
static String room;
private int id;
private static int idCounter=0;//学号计数器
public Student(){
idCounter++;
}
public Student(String name,int age){
this.name=name;
this.age=age;
this.id=++idCounter;
}
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;
}
}
package Demo03;
/*
-
如果一个成员变量使用了static关键字,那么这个变量不再属于自己
-
而是属于所在的类,也就是多个对象共享一个数据
-
*/
public class demo01StaticField {
public static void main(String[] args) {Student one=new Student("郭靖",20); one.room="101教室"; Student two=new Student("黄蓉",16); System.out.println("名前:"+one.getName()+"年齢:"+one.getAge()+"教室:"+one.room+"ID:"+one.getId()); System.out.println("名前:"+two.getName()+"年齢:"+two.getAge()+"教室:"+two.room+"ID:"+two.getId());
}
}