用static声明的成员变量为静态成员变量,也称为类变量,类变量的生命周期和类相同
特点:
- 为该类的公用变量,属于类,被该类的所有实例共享,在类被载入时被显式初始化。
- 对于该类的所有对象来说,static成员变量只有一份。被该类的所有对象共享!
- 一般用“类名.类属性/方法”来调用。(也可以通过对象引用或类名(不需要实例化)访问静态成员。)
- 在static方法中不可直接访问非static的成员。
- this不能用于static方法中
static修饰的成员变量和方法,从属于类。 普通变量和方法从属于对象的。
使用示例:
public class Student {
int id; //学号
String name; //姓名
static String school = "浙江大学"; // 学校名称
public Student(int id, String name) {
this.id = id;
this.name = name;
}
public void info() {
printSchool();
System.out.println(school);
System.out.println("我是:" +name);
}
public static void printSchool() {
//info();//调用非静态成员,编译就会报错
System.out.println(school);
}
public static void main(String[] args) {
Student u = new Student(01, "李华");
Student.printSchool();
Student.school = "深圳大学";
Student.printSchool();
}
}
补充:静态块,静态块中依旧不能调用普通属性和方法
public class Test2 {
public static void main(String[] args) {
}
static { //静态块,在类初始化的时候执行
String name = "小明";
System.out.println("我是静态块");
System.out.println("我是"+name);
}
}