Note that there are some explanatory texts on larger screens.

plurals
  1. PODon’t call subclass methods from a superclass constructor
    text
    copied!<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 noreferrer">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>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload