标签:
面试和笔试中总能遇到这样的问题,像下面一样的代码具体的执行顺序(ABCD都是类)
public class A { public A(String text){ System.out.println("A was built :"+text); } D b1=new D("d in A"); static{ System.out.println("A Static Code out of constructor"); } static D b2=new D("static b in A"); { System.out.println("A Code out of constructor"); } }
之前自己已经知道了,今天复习《Thinking in Java》又看到了这一段,在这里用代码来看看结果。最后给大家一个结论 代码如下(虽然有点长,但是仔细看还是挺简单的)
public class A { public A(String text){ System.out.println("A was built :"+text); } D b1=new D("d in A"); static{ System.out.println("A Static Code out of constructor"); } static D b2=new D("static b in A"); { System.out.println("A Code out of constructor"); } } class B extends A{ static{ System.out.println("B Static Code out of constructor"); } { System.out.println("B Code out of constructor"); } public B(String text){ super(text); System.out.println("B was built :"+text); } } class D{ public D(String text){ System.out.println("D was built :"+text); } public static void fsdaf(){ } } class C{ static{ System.out.println("C static code out of constructor"); } public C(String text){ System.out.println("C was built :"+text); } } class TestABC{ public static void main(String[] args) { // A testA=null; A testA=new A("testA"); System.out.println("********************************"); A testAf=new A("testA"); System.out.println("--------------------------------"); B testB=new B("testB"); System.out.println("********************************"); C testC=new C("testC"); } }
结果如下
A Static Code out of constructor D was built :static b in A D was built :d in A A Code out of constructor A was built :testA ******************************** D was built :d in A A Code out of constructor A was built :testA -------------------------------- B Static Code out of constructor D was built :d in A A Code out of constructor A was built :testB B Code out of constructor B was built :testB ******************************** C static code out of constructor C was built :testC
从上面可以看出,如果没有继承父类 那么执行的顺序是
1.static类型的对象和代码段(那个在前面先执行哪个 且该类没有被实例化过)
2.类中非static的代码段
3.构造函数 如果该类已被实例化过,那么static的内容就不会再次被执行。
如果继承了父类 那么执行顺序是
1.static类型的对象和代码段(那个在前面先执行哪个 且该类没有被实例化过)
2.父类中的代码段
3.父类的构造函数
4.子类中的非静态代码段
5.子类构造函数
另外static的内容并不是代码写好就已经被执行,而是必须在使用到或者实例化的时候才会运行,这一点需要注意
标签:
原文地址:http://www.cnblogs.com/mamuluke/p/5303732.html