首页 > 代码库 > java类初始化

java类初始化

 

 

class SuperClass{
    
    static{
        System.out.println("super class init!");
    }
    static int superInt = 1;
    static String superString = "supString";
}

class SubClass extends SuperClass{

    
    static{
        System.out.println("sub class init!");
    }
    static final String subStringFinal = "subString";
    static String subString = "subString";
}


public class InitTest {

    public static void main(String[] args) {
        //下面这句只会触发父类初始化
        System.out.println(SubClass.superString);
        //下面这句不会出发父类初始化
        SubClass[] subArray = new SubClass[10];
        //下面这句不会出发类初始化,因为在编译阶段,final属性就已加到常量池中了
        System.out.println(SubClass.subStringFinal);
        //下面这句会出发子类初始化
        System.out.println(SubClass.subString);
    }
}