static关键字
1、修饰类属性后,变成静态属性,数据存放在jvm的数据区,数据共享并只有一份
2、修饰类方法后,变成静态方法,静态方法只能访问静态属性,不能访问非静态属性
3、非静态方法可以访问静态属性
4、静态代码块在类加载时执行,并且只执行一次
public class Student {
private String name;
private int age;
private static String nationality;//国籍
static {
//静态代码块
System.out.println("Student 类加载时执行,并且只执行一次");
}
public void test() {
this.name = "张三";
this.age = 18;
nationality = "中国";//编译没问题,非静态方法可以访问静态属性
}
public static void testStatic() {
//this.name = "张三"; //编译报错,静态方法访问了非静态属性
nationality = "中国";
}
public static void main(String[] args) {
Student s1 = new Student();
Student s2 = new Student();
}
}
执行结果(创建了2个实例,static代码块只执行一次):