Java中的静态(static)关键字只能用于成员变量或语句块,以及静态方法。其中成员变量,语句块在类加载时会自动执行,即主动执行,不需要通过对象来执行。静态方法不需要通过对象来调用,没有其他方法调用时不会被执行,属于被动执行。
执行顺序
static 语句的执行时机实在第一次加载类信息的时候(如调用类的静态方法,访问静态成员,或者调用构造函数), static 语句和 static 成员变量的初始化会先于其他语句执行,而且只会在加载类信息的时候执行一次,以后再访问该类或new新对象都不会执行
而非 static 语句或成员变量,其执行顺序在static语句执行之后,而在构造方法执行之前,总的来说他们的顺序如下
1. 父类的 static 语句和 static 成员变量
2. 子类的 static 语句和 static 成员变量
3. 父类的 非 static 语句块和 非 static 成员变量
4. 父类的构造方法
5. 子类的 非 static 语句块和 非 static 成员变量
6. 子类的构造方法
例子1:
package myProj;
public class StaticTest {
public static void main(String[] args){
staticFunection();
}
static StaticTest st = new StaticTest();
static{
System.out.println("1");
}
{
System.out.println("2");
}
public StaticTest() {
// TODO Auto-generated constructor stub
System.out.println("3");
System.out.println("a ="+ a +", b="+b);
}
public static void staticFunection(){
System.out.println("4");
}
int a = 110;
static int b = 112;
}
【输出】
2
3
a =110, b=0
1
4
例子2:
新增class
package myProj;
public class StaticTest1 {
static {
System.out.println("this is static of parent class");
}
{
System.out.println("this is not static of parent class");
}
public StaticTest1 (){
System.out.println("this is parent class");
}
}
修改StaticTest
//static StaticTest st = new StaticTest();
static StaticTest1 st = new StaticTest1();
static StaticTest1 st1 = new StaticTest1();
【输出结果】
this is static of parent class
this is not static of parent class
this is parent class
this is not static of parent class
this is parent class
1
4
其中静态代码块只被执行了一次