当 static 修饰成员变量时,该变量称为类变量。该类的每个对象都共享同一个类变量的值。任何对象都可以更改该类变量的值,但也可以在不创建该类的对象的情况下对类变量进行操作。
格式:
static 数据类型 变量名;
public class Student {
//成员变量
private String name;
private int age;
// 类变量,记录学生学习的学校
public static String school = "清华大学";
public Student(String name, int age){
this.name = name;
this.age = age;
}
// 打印属性值
public void show() {
System.out.println("name=" + name + ", age=" + age + ", shool=" + shool );
}
}
//测试类
public class StuDemo {
public static void main(String[] args) {
Student s1 = new Student("张三", 23);
Student s2 = new Student("李四", 24);
Student s3 = new Student("王五", 25);
Student s4 = new Student("赵六", 26);
s1.show(); // Student : name=张三, age=23, shool=清华大学
s2.show(); // Student : name=李四, age=24, shool=清华大学
s3.show(); // Student : name=王五, age=25, shool=清华大学
s4.show(); // Student : name=赵六, age=26, shool=清华大学
}
}