一、先执行内部静态对象的构造方法,如果有多个按定义的先后顺序执行;静态对象在构造的时候也是也先执行其内部的静态对象。
二、再调用父类的构造方法(父类还有父类的话,从最开始的基类开始调用),如果没有明显指定调用父类自定义的构造方法,那么编译器会调用默认的父类构造方法super()。但是如果要调用父类自定义的构造方法,要在子类的构造方法中明确指定。
三、按声明顺序将成员引用对象变量初始化。
四、最后调用自身的构造方法。
下面以一个例子来说明代码如下:
class Animal{
String name;
Animal() {
System.out.println("class Animal");
}
Animal(String name){
this.name = name;
System.out.println(name + " class Animal");
printNumber();
}
public void printNumber(){
}
}
class Fish extends Animal{
Fish() {
System.out.println("class Fish");
}
}
class GoldFish extends Fish {
GoldFish() {
System.out.println("class GoldFish");
}
}
class Cat {
Cat(){
System.out.println("class cat");
}
}
class Rabbit {
private static int number;
private static Cat cat = new Cat();
public Rabbit() {
number++;
System.out.println(number + "class rabbit");
}
}
class Dog extends Animal{
public int dogNumber;
private GoldFish goldFish = new GoldFish();
static Rabbit blackRabbit = new Rabbit();
static Rabbit whiterabbit = new Rabbit();
public Dog() {
super("Tom");
System.out.println("class Dog");
dogNumber = 10;
System.out.println("The dog's number is:" + dogNumber);
}
public void printNumber(){
System.out.println("The dog's number is:" + dogNumber);
}
}
public class TestInheritanceConstructor extends Animal {
public static void main(String[] args){
new Dog(); //Test the executive order of constructor
}
}
class Animal{
String name;
Animal() {
System.out.println("class Animal");
}
Animal(String name){
this.name = name;
System.out.println(name + " class Animal");
printNumber();
}
public void printNumber(){
}
}
class Fish extends Animal{
Fish() {
System.out.println("class Fish");
}
}
class GoldFish extends Fish {
GoldFish() {
System.out.println("class GoldFish");
}
}
class Cat {
Cat(){
System.out.println("class cat");
}
}
class Rabbit {
private static int number;
private static Cat cat = new Cat();
public Rabbit() {
number++;
System.out.println(number + "class rabbit");
}
}
class Dog extends Animal{
public int dogNumber;
private GoldFish goldFish = new GoldFish();
static Rabbit blackRabbit = new Rabbit();
static Rabbit whiterabbit = new Rabbit();
public Dog() {
super("Tom");
System.out.println("class Dog");
dogNumber = 10;
System.out.println("The dog's number is:" + dogNumber);
}
public void printNumber(){
System.out.println("The dog's number is:" + dogNumber);
}
}
public class TestInheritanceConstructor extends Animal {
public static void main(String[] args){
new Dog();//Test the executive order of constructor
}
}执行结果:
class cat
1class rabbit
2class rabbit
Tom class Animal
The dog's number is:0
class Animal
class Fish
class GoldFish
class Dog
The dog's number is:10
解释:
输出:class cat 是因为Dog类中有静态成员。而静态成员所在的类Rabbit中又有静态成员。所以最先执行它。验证第 一句。
输出:1class rabbit 和 2class rabbit 是执行类Rabbit构造函数。
输出:Tomclass Animal 执行父类的构造函数,因为用super("")。
输出:The dog's number is:0 可以看出子类的dogNumber还是默认值0
输出:class Animal 和 class Fish 和 class GoldFish是构造goldFish引用对象类型。验证第三句。
输出:class Dog 和The dog's number is:10是执行自己的构造函数。