问题:
子类继承父类,构造函数及公共属性的执行顺序是怎样的?
示例代码
[java] <span style="font-family:Times New Roman;font-size:14px;">public class A extends C { B b = new B(); static H h = new H(); static { System.out.println("this is static tack"); } static void i() { System.out.println("this is static metod"); } public A() { System.out.println("this is class A"); } public static void main(String[] args) { A a = new A(); } } class B { public B() { System.out.println("this is class B"); } } class C { D d = new D(); static E e = new E(); final F e1 = new F(); static final G e2 = new G(); public C() { System.out.println("this is class C"); } } class D { public D() { System.out.println("this is class D"); } } class E { public E() { System.out.println("this is class E"); } } class F { public F() { System.out.println("this is class F"); } } class G { public G() { System.out.println("this is class G"); } } class H { public H() { System.out.println("this is class H"); } }</span> 执行结果:
this is class E this is class G this is class H this is static tack this is class D this is class F this is class C this is class B this is class A
执行顺序:
1、实现父类公共的静态属性或静态的块级代码
2、实现本身的公共的静态属性
3、实现父类公共属性
4、执行父类的构造方法
5、实现本身的公共属性
6、执行本身的构造函数
7、静态方法不执行
补充:
当父类有多个构造函数,若子类用super(参数信息)指明调用父类有参数的构造函数,则不执行无参数的构造方法
|