How does the JVM initiate fields in super and subclasses?

Can any authority tell why the output of the following code is "null"? What's the best way to build a complex object and delegate the details to their subclasses?


package com.test;

public class ClassA {

    ClassA() {
        initHeader();
        initBody();
        initFooter();
    }

    void initHeader() {}

    void initBody() {}

    void initFooter() {}

    public static void main(String[] args) {
        ClassB a = new ClassB();
        System.out.println(a.obj);
    }
}

class ClassB extends ClassA {

    public Object obj = null;

    ClassB() {
        super();
    }

    void initHeader() {
        obj = new Object();
    }

}



      

+3


source to share


2 answers


First, the fields are ClassA

initialized.

Then the constructor is called by ClassA

calling ClassB.initHeader()

.



The fields are then ClassB

initialized, overriding execution initHeader()

.

+8


source


It is wrong that this code does not call initHeader

from ClassB. You can test it by adding debug output to methods initHeader

for both classes.

public Object obj = null;

contain two parts:

  • Ad public Object obj

  • Performance obj = null



The first part, known when the constructor is run (currently obj is initialized as null

the default) The second part is done after the constructor , so after initHeader

and override obj.

Try to just replace public Object obj = null;

withpublic Object obj;

+1


source







All Articles