Call a method after the constructor has ended

You will need a static factory method to construct the object, call the init method, and finally return the object:

class A {
    private A() {
        //...
    }

    private void init() {
        //Call after the constructor
    }

    public static A create() {
        A a = new A();
        a.init();
        return a;
    }
}

Notice I have made the constructor and the init() method private, so that they can only be accessed by the factory method. Client code would make objects by calling A.create() instead of calling the constructor.


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

What did you so far? Are you looking something like this?

  Class A {
        public A() {
            //...
        }

        public void init() {
            //Call after the constructor
        }
    }

     public static void main(String[] args)
    {
    A a = new A();

    a.init();
}

Tags:

Java