Home > Java, Tech > Java: Calling overriden method in superclass constructor

Java: Calling overriden method in superclass constructor


A commonly occurring inheritance design is to have an abstract method in the superclass which is called in the superclass constructor as a way to let subclasses change the way the object is initialized. For example:

Superclass:


public abstract class Super {
  public Super() {
    loadConfig();
  }

  protected abstract void loadConfig();
}

Subclass:


public class Sub extends Super {

  protected String var;

  protected void loadConfig() {
    var = "loaded_config";
  }
}

The idea is to enforce the constraint that the loadConfig method is always called in the constructor of the object, how the configuration is to be loaded exactly is left to the subclasses.

This however does not work a expected


public class Test {
  Sub s = new Sub();
  System.out.println("var value: " + s.var);
}

The output is not “var value: loaded_config” as a lot of us would expect. it’s “var value: null”.
To understand why, change the Sub class to this:


public class Sub extends Super {

  protected String var = setMeth();

  private String setMeth() {
    System.out.println("Setting member variable with setMeth");
    return "setMeth value";
  }

  protected void loadConfig() {
    System.out.println("Setting member variable with loadConfig");
    var = "loaded_config";
  }
}

Now the output should be:


Setting member variable with loadConfig
Setting member variable with setMeth
var value: setMeth value

What happens is that in the subclass constructor, the superclass constructor is called before the subclass object is created (that is why you always need to put calls to super() as the first statement). As a result, although the overriden method does it’s job fine in setting the value of the variable the way we want, just after this happens (from inside the super class ctor), the sub class object is initialized and the value for the member variable is overwritten (by the setMeth in second case and as the default null in the first).

The only way out of this (that I know!) is to move this obligation of calling the loadConfig method on to the subclass implementation code (which is clearly not anyone’s first choice 😦 )

  1. May 13, 2014 at 10:46 pm

    Hi there great blog! Does running a blog like this take a massive amount work?

    I’ve very little understanding of computer programming however I had been hoping
    to start my own blog soon. Anyway, should you have any suggestions or techniques for
    new blog owners please share. I understand this is
    off subject however I just needed to ask. Thanks!

  1. April 3, 2010 at 1:46 am
  2. July 4, 2010 at 12:45 am

Leave a comment