mCoder mCoder - 6 months ago 18
Java Question

Java equivalent of instance initializer called after constructor

I've been reading about instance initializers in Java, and it's been explained that code common to all constructors can be put into them because they are called every time a new instance of a class is created. Is there an equivalent of instance initializers that run after constructors, for code that would be common to all constructors, but depends on what happens in the constructors?

Answer

No, there isn't an exact equivalent. If you want to run some common code, you can always factor out a method and call it at the end of all your constructors:

public class C {
    private int x = 5;
    private String y;

    public C(int x) {
        this.x = x;
        endConstructor();
    }

    public C(String x) {
        this.x = x.length;
        endConstructor();
    }

    private void endConstructor() {
        y = x + "!";
    }
}

Sometimes, what seems like a situation where you want to call the same code at the "end" of all constructors can be refactored so that this code is in a single main constructor. Then, all other constructors call it using this(). For the example above:

public class C {
    private int x = 5;
    private String y;

    public C(int x) {
        this.x = x;
        y = x + "!";
    }

    public C(String x) {
        this(x.length);
    }
}

The main constructor can be private, if appropriate.

Comments