public class B { public static B t1 = new B(); public static B t2 = new B(); { System.out.println("构造块"); } static { System.out.println("静态块"); } public static void main(String[] args) { B t = new B(); } }
public class B { public static B t1 = new B(); public static B t2 = new B(); { System.out.println("构造块"); } static { System.out.println("静态块"); } public static void main(String[] args) { B t = new B(); } }
静态块 构造块 构造块 构造块
构造块 静态块 构造块 构造块
构造块 构造块 静态块 构造块
构造块 构造块 构造块 静态块
public static B t1 = new B(); public static B t2 = new B(); 所以会打印两个“构造块” 接着在执行静态代码块 打印“静态块”, 最后执行B t = new B(); 打印“构造块”
public class HelloB extends HelloA { public HelloB(){ System.out.println("B的构造方法"); } { System.out.println("B的构造代码块"); } static{ System.out.println("B的静态代码块"); } //public static HelloB hB = new HelloB(); public static void main(String[] args){ new HelloB();//调用B的构造方法 } } class HelloA{ public HelloA(){ System.out.println("A的构造方法"); } { System.out.println("A的构造代码块"); } static{ System.out.println("A的静态代码块"); } }