Don’t call subclass methods from a superclass constructor
<p>Consider the following code</p>

<pre><code>/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package example0;

/**
 *
 * @author yccheok
 */
public class Main {

    static class A {
        private final String var;

        public A() {
            var = getVar();
            // Null Pointer Exception.
            System.out.println("var string length is " + var.length());
        }

        public String getVar() {
            return "String from A";
        }
    }

    static class B extends A {
        private final String bString;

        // Before B ever constructed, A constructor will be called.
        // A is invoking a overriden getVar, which is trying to return
        // an initialized bString.
        public B() {                
            bString = "String from B";
        }

        @Override
        public String getVar() {
            return bString;
        }
    }

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        B b = new B();
    }

}
</code></pre>

<p>Currently, in my mind, there are two ways to avoid such problem.</p>

<p>Either making class A final class.</p>

<pre><code>static final class A {
    private final String var;

    public A() {
        var = getVar();
        // Null Pointer Exception.
        System.out.println("var string length is " + var.length());
    }

    public String getVar() {
        return "String from A";
    }
}
</code></pre>

<p>Or</p>

<p>Making getVar method final</p>

<pre><code>static class A {
    private final String var;

    public A() {
        var = getVar();
        // Null Pointer Exception.
        System.out.println("var string length is " + var.length());
    }

    public final String getVar() {
        return "String from A";
    }
}
</code></pre>

<p>The author trying to suggest ways to prevent the above problem. However, the solution seems cumbersome as there are some rules to be followed.</p>

<p><a href="http://benpryor.com/blog/2008/01/02/dont-call-subclass-methods-from-a-superclass-constructor/" rel="nofollow">http://benpryor.com/blog/2008/01/02/dont-call-subclass-methods-from-a-superclass-constructor/</a></p>

<p>Beside making final and the author suggested way, is there more ways to prevent the above problem (Don’t call subclass methods from a superclass constructor) from happen?</p>
