Calling Method from Constructor

Can I call methods in constructor in Java?

Better design would be

public static YourObject getMyObject(File configFile){
//process and create an object configure it and return it
}
  • Factory design pattern

Why is it considered bad practice in Java to call a method from within a constructor?

First, in general there's no problem with calling methods in a constructor. The issues are specifically with the particular cases of calling overridable methods of the constructor's class, and of passing the object's this reference to methods (including constructors) of other objects.

The reasons for avoiding overridable methods and "leaking this" can be complicated, but they basically are all concerned with preventing use of incompletely initialised objects.

Avoid calling overridable methods

The reasons for avoiding calling overridable methods in constructors are a consequence of the instance creation process defined in §12.5 of the Java Language Specification (JLS).

Among other things, the process of §12.5 ensures that when instantiating a derived class[1], the initialisation of its base class (i.e. setting its members to their initial values and execution of its constructor) occurs before its own initialisation. This is intended to allow consistent initialisation of classes, through two key principles:

  1. The initialisation of each class can focus on initialising only the members it explicitly declares itself, safe in the knowledge that all other members inherited from the base class have already been initialised.
  2. The initialisation of each class can safely use members of its base class as inputs to the initialisation of its own members, as it is guaranteed they've been properly initialised by the time the initialisation of the class occurs.

There is, however, a catch: Java allows dynamic dispatch in constructors[2]. This means that if a base class constructor executing as part of the instantiation of a derived class calls a method that exists in the derived class, it is called in the context of that derived class.

The direct consequence of all of this is that when instantiating a derived class, the base class constructor is called before the derived class is initialised. If that constructor makes a call to a method that is overridden by the derived class, it is the derived class method (not the base class method) that is called, even though the derived class has not yet been initialised. Evidently this is a problem if that method uses any members of the derived class, since they haven't been initialised yet.

Clearly, the issue is a result of the base class constructor calling methods that can be overriden by the derived class. To prevent the issue, constructors should only call methods of their own class that are final, static or private, as these methods cannot be overridden by derived classes. Constructors of final classes may call any of their methods, as (by definition) they cannot be derived from.

Example 12.5-2 of the JLS is a good demonstration of this issue:

class Super {
Super() { printThree(); }
void printThree() { System.out.println("three"); }
}
class Test extends Super {
int three = (int)Math.PI; // That is, 3
void printThree() { System.out.println(three); }

public static void main(String[] args) {
Test t = new Test();
t.printThree();
}
}

This program prints 0 then 3. The sequence of events in this example is as follows:

  1. new Test() is called in the main() method.
  2. Since Test has no explicit constructor, the default constructor of its superclass (namely Super()) is called.
  3. The Super() constructor calls printThree(). This is dispatched to the overriden version of the method in the Test class.
  4. The printThree() method of the Test class prints the current value of the three member variable, which is the default value 0 (since the Test instance hasn't been initialised yet).
  5. The printThree() method and Super() constructor each exit, and the Test instance is initialised (at which point three is then set to 3).
  6. The main() method calls printThree() again, which this time prints the expected value of 3 (since the Test instance has now been initialised).

As described above, §12.5 states that (2) must happen before (5), to ensure that Super is initialised before Test is. However, dynamic dispatch means that the method call in (3) is run in the context of the uninitialised Test class, leading to the unexpected behaviour.

Avoid leaking this

The restriction against passing this from a constructor to another object is a little easier to explain.

Basically, an object cannot be considered fully initialised until its constructor has completed execution (since its purpose is to complete the initialisation of the object). So, if the constructor passes the object's this to another object, that other object then has a reference to the object even though it hasn't been fully initialised (since its constructor is still running). If the other object then attempts to access an uninitialised member or call a method of the original object that relies on it being fully initialised, unexpected behaviour is likely to result.

For an example of how this can result in unexpected behaviour, please refer to this article.



[1] Technically, every class in Java except Object is a derived class - I just use the terms 'derived class' and 'base class' here to outline the relationship between the particular classes in question.

[2] There's no reason given in the JLS (as far as I'm aware) as to why this is the case. The alternative - disallowing dynamic dispatch in constructors - would make the whole issue moot, which is probably exactly why C++ doesn't allow it.

Calling method from constructor

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.

Calling a class method from the constructor

You're calling the function init(), not the method init of either Base or the current object. No such function exists in the current scope or any parent scopes. You need to refer to your object:

this.init();

Calling methods from the constructor

TLDR In my opinion, using methods inside of a constructor is a sign of bad design. If you aren't looking for design advice, then the answer "no there's nothing wrong with it, technically speaking, as long as you avoid calling non-final methods" should do you fine. If you ARE looking for design advice, see below.

I think your example code is not good practice at all. In my opinion, a constructor should only receive values which is relevant to it and should not need to perform any other initialization on those values. There's no way for you to test that your constructor 'works' with all of those little extra steps - all you can do is construct the object and hope that everything ends up in the correct state. Further, your constructor ends up with more than one reason to change, which violates the SRP.

class Info {
public RoadInfo(String cityName, double lat, double lng) throws FileNotFoundException, SAXException, IOException, XPathExpressionException {
// TODO Auto-generated constructor stub
this.cityname = cityName;
this.lat = lat;
this.lng = lng;

this.path = "c:"+File.separatorChar+this.cityname+".xml";

System.out.println(path);

this.initXPath();
this.method1()
this.method2()
..

this.expr = "//node[@lat='"+this.lat+"'"+"]/following-sibling::tag[1]/@v";
this.xPath.compile(this.expr);
String s = (String) this.xPath.evaluate(this.expr, this.document, XPathConstants.STRING);
System.out.println(s);
}

So, for example, this constructor is loading a file, parsing it in XPath.. if I ever want to create a RoadInfo object, I can now only do it by loading files and having to worry about exceptions being thrown. This class also now becomes hilariously difficult to unit test because now you can't test the this.initXPath() method in isolation, for example - if this.initXPath(), this.method1() or this.method2() have any failures, then every one of your test cases will fail. Bad!

I would prefer it to look something more like this:

class RoadInfoFactory {
public RoadInfo getRoadInfo(String cityName, double lat, double lng) {
String path = this.buildPathForCityName(cityName);
String expression = this.buildExpressionForLatitute(lat);
XPath xpath = this.initializeXPath();
XDocument document = ...;

String s = (String) xpath.evaluate(expression, document, XPathConstants.STRING);
// Or whatever you do with it..
return new RoadInfo(s);
}
}

Never mind the fact that you have at least 5 responsibilities here.

  • Build OS-neutral path
  • Build XPath expression for latitude/longitude
  • Create XPath doocument
  • Retrieve s - whatever that is
  • Create new RoadInfo instance

Each of these responsibilities (Except the last) should be separated into their own classes (IMO), and have RoadInfoFactory orchestrate them all together.

Call static method from constructor in Java

Even though it's possible to do so, do not call methods from constructors.

Well, as I already said in the comments, it's perfectly fine to call methods from constructors. Either the author doesn't really understand it all, or this sentence is poorly-worded.

  • Calling overridable methods of the instance you're currently constructing will cause problems, as it'll leak half-constructed objects. See here for more info. But it looks like you're already aware of this.

  • Also, if you pass this to another method from within a constructor, then you're passing the half-constructed instance. Bad. Don't do it.

But for all other cases, calling another method will cause no problem at all. When you call a method, it is executed, and when it returns, control is passed back to the constructor, which happily continues with constructing the object.

There is absolutely no problem with your code:

TestClass(int number) {
if (NumberUtils.isGreaterThanOne(number)) {
this.number = number;
} else {
throw new IllegalArgumentException("Number must be above 1");
}
}

If it were bad to call other methods from the constructor, you had to implement the check employed by isGreaterThanOne all here in the constructor itself. But instead, you happily delegate this to a separate method, which can be separately tested. So you're actually validating the input, which should be done.


Another way to write the validation, is to write guard clauses:

TestClass(int number) {
// This check here immediately throws an exception if number has an
// invalid value. This is called a a guard clause, and are usually
// positioned at the top of the method or constructor.
if (!NumberUtils.isGreaterThanOne(number)) {
throw new IllegalArgumentException("Number must be above 1");
}

// Continue with normal operation
}

But this is just another way of writing the same logic.

Call a method after the constructor has ended

You either have to do this on the client side, as so:

A a = new A();
a.init();

or you would have to do it in the end of the constructor:

class A {
public A() {
// ...
init();
}

public final void init() {
// ...
}
}

The second way is not recommended however, unless you make the method private or final.


Another alternative may be to use a factory method:

class A {
private A() { // private to make sure one has to go through factory method
// ...
}
public final void init() {
// ...
}
public static A create() {
A a = new A();
a.init();
return a;
}
}

Related questions:

  • What's wrong with overridable method calls in constructors?
  • Java call base method from base constructor

Can't call method from constructor

Change the methods you are calling from other methods to this

export class Init {

constructor(private connectBtn: HTMLElement) {
this.setEventHandler();
}

public setEventHandler = () => {
this.connectBtn.onclick = (e) => {
this.openConnectWindow();
}
}

private openConnectWindow = () => {
console.log("OPEN SESAME")
}
}

Call method in constructor

If I understand correctly your question, you simply want to add some statements to the main constructor body? If that's the case, you can simply do so in the body of the class itself. In your case, that would look like this:

class SteamController @Inject()(cache: CacheApi) extends BaseController {

...

private val GAME_KEY: String = "games"

loadGameIds() // <-- Here we are calling from the main constructor body

def games = Action { implicit request =>
...
}

...
}

When doing so, it is usually a good idea to perform additional code after the declaration of all vals and vars in your class, to ensure they are properly initialized at the time your additional constructor code runs.

Call Method from Constructor: Error: Uncaught TypeError: undefined is not a function

Here's how to call a method from the constructor:

class Thing {
constructor(name: string) {
this.greet(name);
}

greet(whatToGreet: string) {
console.log('Hello, ' + whatToGreet + '!')
}
}

var x = new Thing('world'); // Prints "Hello, world!"


Related Topics



Leave a reply



Submit