先看一段代码:
//Student类
public class Student {
String name;
int age;
static String country ;//静态修饰的成员变量
public Student(){}
public Student(String name,int age,String country){
this.name = name;
this.age = age;
this.country = country;
}
//成员方法
public void show(){
System.out.println(name+","+age+","+country);
}
}
//测试类
public class Test2 {
public static void main(String[] args){
Student.country ="中国";
//创建学生对象
Student s1 = new Student();
s1.name="小哀";
s1.age=20;
s1.show();
Student s2 = new Student();
s2.name="小兰";
s2.age=19;
s2.country="Japan";//给小兰的country赋值
s2.show();
Student s3 = new Student();
s3.name = "新一";
s3.age = 19;
s3.show();
Student s4 = new Student();
s4.name = "小朱";
s4.age = 23;
s4.country = "Chinese";//给小朱的country赋值
s4.show();
Student s5 = new Student();
s5.name = "小丽";
s5.age = 21;
s5.show();
}
}
输出结果:
小哀,20,中国
小兰,19,Japan
新一,19,Japan
小朱,23,Chinese
小丽,21,Chinese
虽然static 可以使contry让所有对象共享,但如果单独给一个对象的country赋值,下面新创建的对象的country不赋值的话,他们的country值和这一对象的country值相同.
如果想让所有对象共享这一成员变量,并不能改变,可以再给这一成员变量加上final,测试类中也不能再给country赋值:
//Student类
public class Student {
String name;
int age;
static final String country ;//静态修饰的成员变量,加上final,值无法改变
public Student(){}
public Student(String name,int age){//构造方法中也不用给country初始化
this.name = name;
this.age = age;
}
//成员方法
public void show(){
System.out.println(name+","+age+","+country);
}
}