Can any body tell why the output of following code is "null"? And what is the best way to construct 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();
    }

}


有帮助吗?

解决方案

First, the fields of ClassA are initialized.

The constructor of ClassA is then called, calling ClassB.initHeader().

After that, fields of ClassB are initialized overriding what initHeader() had done.

其他提示

It's not correct that this code doesn't call initHeader from ClassB. You can verify it by adding debug output to initHeader methods of both class.

public Object obj = null; contain two parts:

  1. declaration public Object obj
  2. execution obj = null

First part known when constructor runs (at this moment obj initialised as null by default) Second part executed after constructor, so after initHeader and override obj.

Try just replace public Object obj = null; by public Object obj;

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top