Java constructor execution order

  • First, the base class constructor is executed
  • Then initialization statements executed outside the constructor of the derived class
  • Finally, the derived class's constructor executes

In Java, if the derived class constructor needs to call the base class constructor, then the base class constructor must be the first word derived class constructor. In Python, the derived class calls the base class constructor is relatively flexible.

The following code have a base class Base, a derived class Son, Son a member variable Value. Son When creating an object, the order of execution of the base class constructor, the constructor of Value, Son constructor.

package weiyinfu.colorama;

public class Why {
class Base {
    Base() {
        System.out.println("base is called");
    }
}

class Value {
    Value() {
        System.out.println("value is called");
    }
}

class Son extends Base {
    Value v = new Value();

    Son() {
        System.out.println("son is called");
    }
}

public static void main(String[] args) {
    Why y = new Why();
    Son s = y.new Son();
}
}

Guess you like

Origin www.cnblogs.com/weiyinfu/p/11098902.html