9.13 static关键字

static这个关键字在很早我们就接触过了,它出现在main函数的声明里。后来我们知道,static关键字修饰的变量、方法,都是不依赖对象而存在的。并且是对象都共用的。我们在类属性和类方法可以看到这些概念。
但接下来我们接触static另一种用法:

public class Test{private int one;private static int FIX;static {FIX = 0;welcome("");}public static void welcome(String name) {System.out.println("欢迎你," + name);}}

这里的static{},大括号内部可以给static类型的变量赋值,可以调用static函数,但是这里不能调用非static方法,也不能给非static变量赋值,例如类里面的变量one。
更重要的是:static代码块,执行比构造函数还要早,但是只执行一次。

public class Test{private int one;private static int FIX;static {FIX = 0;welcome("abc");}public static void welcome(String name) {System.out.println("欢迎你," + name);}public Test(){System.out.println("construct");}public static void main(String[] args) {Test f=new Test();Test f2=new Test();}}

这段代码将打印:
欢迎你,abc
construct
construct

首先class装载完毕,就调用static代码块,里面有一个welcome静态方法,所以打印了“欢迎你,abc”,然后执行main函数,调用了两个构造函数,打印了两个“construct”。