构造器初始化顺序如下:
1 基类static成员初始化
2 子类static成员初始化
3 基类对象成员默认初始化(按照声明的顺序)
4 子类成员默认初始化(按照声明的顺序)
5 子类构造函数调用父类构造函数(如果子类构造器中没有显式的调用父类构造函数,那么父类必须提供一个无参构造器供子类调用。如果所有子类构造器中显式调用父类其他的构造函数,那么就不会执行父类默认构造函数,并且编译时不会强制父类提供默认构造函数)
6 子类构造函数执行
下面的代码输出结果如下:
Base Static Init
Derived Static Init
BaseInit with args:0
DerivedInit
--------------------
BaseInit with args:1
DerivedInit with args:1- class Puppy{
- public Puppy(String name)
- {
- System.out.println( name);
- }
- }
- class BaseInit{
- public static Puppy basePuppy = new Puppy("Base Static Init");
- /* Unless every derived class's constructors call base class's constructors
- * explicitly, base class must have a default constructor
- */
- /*
- public BaseInit()
- {
- System.out.println("BaseInit");
- }
- */
- public BaseInit(Integer i)
- {
- System.out.println("BaseInit with args:"+i);
- }
- }
- class DerivedInit extends BaseInit{
- public static Puppy derivedPuppy= new Puppy("Derived Static Init");
- public DerivedInit()
- {
- /* call base class's constructor explicitly */
- super(0);
- System.out.println("DerivedInit");
- }
- public DerivedInit(Integer i)
- {
- super(i);
- System.out.println("DerivedInit with args:"+i);
- }
- }
- public class InitOrder {
- public static void main(String args[]){
- DerivedInit derivedInit = new DerivedInit();
- System.out.println("--------------------");
- DerivedInit derivedInit2 = new DerivedInit(1);
- }
- }
复制代码 |