Java – Calling Method from Constructor

classconstructorjava

Excuse any minor syntax errors or whatnot, I'm experiencing this with a Jitsi module and not being super familiar with Java want to confirm what is going on and why and how it should be fixed.

 public abstract class A
{
  public A()
  {
    this.load();
  }

  protected void load()
  {

  }
}

public class B extends A
{
  private String testString = null; 

  public B()
  {
    super();
  }

  @Override
  protected void load()
  {
    testString = "test";
  }
}

The application is doing this when creating an instance of the class B using a load class by name method:

  • Calls overridden load() in class B
  • Initializes variables (calls "private string testString = null" according to debugger), nulling them out.

Is this expected Java behavior? What could cause this? It's a Java 1.6 application running on the 1.7 JDK.

Best Answer

Is this expected Java behavior?

Yes.

What could cause this?

Your invocation of non-final overridden method in non-final super class constructor.

Let's see what happens step-by-step:

  • You create an instance of B.
  • B() calls super class constructor - A(), to initialize the super class members.
  • A() now invokes a non-final method which is overridden in B class, as a part of initialization.
  • Since the instance in the context is of B class, the method load() invoked is of B class.
  • load() initializes the B class instance field - testString.
  • The super class constructor finishes job, and returns (Assuming chaining of constructor till Object class have been finished)
  • The B() constructor starts executing further, initializing it's own member.
  • Now, as a part of initilization process, B overwrites the previous written value in testString, and re-initializes it to null.

Moral: Never call a non-final public method of a non-final class in it's constructor.

Related Question