static小结
static修饰符
static修饰符通常用来修饰类中方法或属性,在实例化对象时和类一起加载,可以通过类名.方法或类名.属性的方式调用
静态方法可以直接调用静态方法
静态方法不可以直接调用非静态方法
非静态方法可以直接调用静态方法
静态代码块
静态代码块在实例化对象时和类一起加载,加载优先级在匿名代码块和构造方法之前
源代码
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
| public class Student { static { System.out.println("静态代码块"); }
{ System.out.println("匿名代码块"); }
public Student() { System.out.println("构造方法"); }
public static void main(String[] args) { Student student1 = new Student(); System.out.println("============================"); Student student2 = new Student(); } }
|
运行结果

静态导入包(拓展)
在使用关键字import导入包的时候 可以加入static修饰符实现静态导入包中方法
源代码
1 2 3 4 5 6 7
| import static java.lang.Math.PI;
public class Person { public static void main(String[] args) { System.out.println(PI); } }
|