19

I need to call a method after the constructor has ended, and I have no idea what is the better approach.

I have this class:

class A {
    public A() {
        // ...
    }
        
    public void init() {
        // call after the constructor
    }
}

How do I call init() after the class A has been created?

1
  • 1
    Some answers seem to be assuming that the init can simply be moved inside the constructor, but I assume that whatever it is doing is not appropriate to be done in the constructor (such as registering listeners, which would then have a chance to see a partially constructed object), otherwise there would be no need for the question. Dec 12, 2014 at 22:36

6 Answers 6

21

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:

12
  • If init() starts a new thread or shares its this reference with another class that may access the reference from another thread, you should not call it in the constructor. If you do, you'll have a data race.
    – yshavit
    Dec 12, 2014 at 22:35
  • The same problem applies if you do it directly in the constructor. There's no difference if you delegate part of the construction to the init method. What is a problem is when the init method may be overridden by subclasses.
    – aioobe
    Dec 12, 2014 at 22:37
  • You probably want to make the init method private as well if you go the static factory method route. It does make a difference if the issue is sharing the this reference with other threads, since once the constructor completes the class's invariants are presumably ensured and particularly any final fields will be guaranteed to be visible from other threads. Dec 12, 2014 at 22:40
  • @aioobe The fact that inlining it also has that bug doesn't detract from my comment, imho. init() methods often publish this or spin off threads -- that's commonly why they're separate methods as opposed to just being in the constructor. Given that the construct-than-init pattern has a relatively high correlation with init-does-thread-stuff, I thought it'd be helpful to point that danger out explicitly.
    – yshavit
    Dec 12, 2014 at 22:50
  • 1
    Well, I guess we just won't see eye to eye on the relevance of my comment, then. So I'll just leave it as a note to the OP: if your init() method exposes this to anyone (another thread, another class, etc) you're exposing yourself to subtle data race bugs. Do so at your own peril.
    – yshavit
    Dec 12, 2014 at 22:58
4

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.

6
  • 1
    Good idea, but you don't need a factory, if the stuff is private. You could simply call it at the end of the constructor. But you can use a factory as a good solution, if the method and constructor are protected, to ensure, that overriding the constructor does not result in a missing init() call. EDIT of course, if the constructor is protected and the class is abstractable, you need a more generic factory method - forgot to mention that.
    – UniversE
    Dec 12, 2014 at 22:37
  • 1
    @UniversE No, you can't simply call it at the end of the constructor. Java makes special guarantees about the visibility of final fields after the constructor has completed. If you pass a reference to the object to another thread, it could see default values for those fields, which cannot happen after the constructor has finished. Dec 12, 2014 at 22:42
  • But if you call it at the end of the constructor, the method would execute on the same thread, and there would be no visibility issues.
    – aioobe
    Jun 25, 2016 at 6:50
  • @aioobe if you call it at the end of the constructor, and init() lets a reference to this escape, another thread could examine the object before the constructor finishes. See yshavit's comments on another answer to this question. Jun 25, 2016 at 15:03
  • Letting this escape before the object has been fully initialized is a terrible idea, regardless if it's done from the constructor or from an init method, and regardless if there are multiple threads or not.
    – aioobe
    Jun 25, 2016 at 15:35
1

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();
}
1

I pick up some ideas and provide an abstractable solution:

class A {
    protected A() {
        // ...
    }
    protected void init() {
        // ...
    }
    public static <T extends A> T create(Class<T> type) {
        try {
            T obj = type.newInstance();
            obj.init();
            return obj;
        } catch (ReflectiveOperationException ex) {
            System.err.println("No default constructor available.");
            assert false;
            return null;
        }
    }
}
1
  • 1
    As far as I can tell, this is the only answer working with inheritance. Or am I wrong? Dec 12, 2014 at 23:40
1

If you want to call method BEFORE constructor you can use initializer block. https://www.geeksforgeeks.org/g-fact-26-the-initializer-block-in-java/

class A {
    { 
        init() 
    }

    public A() {
        //todo
    }

    private final void init() {
       //todo
    }
}
0
-2

Why not this :

Class A {
    public A() {
        //... Do you thing
        this.init();
    }

    public void init() {
        //Call after the constructor
    }
}
1
  • The constructor is not complete in this case. The constructor completes AFTER this.init() is run. In general, it is not good practice to run methods using this inside its own constructor because the constructor is not fully created. Usually this messes things up when you have multiple threads. May 15, 2019 at 4:26

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.