Java object initialization sequence validation example

  • 2020-04-01 02:53:52
  • OfStack


public class Derive extends Base 
{
    private Member m1 = new Member("Member 1");
    {
        System.out.println("Initial Block()");
    }
    public Derive() {
        System.out.println("Derive()");
    }
    private Member m2 = new Member("Member 2");
    private int i = getInt();
    private int getInt() 
    {
        System.out.println("getInt()");
        return 2;
    }
    public static void main(String[] args)
    {
        new Derive();
    }
}
class Base
{
    public Base() 
    {
        System.out.println("Base()");
    }
}
class Member 
{
    public Member(String m) 
    {
        System.out.println("Member() "+m);
    }
}



Conclusions are as follows: don't consider static initialization, call an object's constructor, program calls the superclass constructor first (by the super keyword specifies the parent class constructor, otherwise the default calling a no-parameter constructor, and the need to in the first line of the subclass constructor function calls), then the static member variable initialization function and static initialization blocks, in the order in the midst of code executed, member variables if there is no specified values to a default value, namely the basic data types to 0 or false, object to null; Finally, the self constructor is called.


Related articles: