Call a method after the constructor has ended

前端 未结 7 849
迷失自我
迷失自我 2020-12-31 07:19

I need to call a method after the constructor has ended and I have no idea how to do. I have this class:

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

             


        
7条回答
  •  长发绾君心
    2020-12-31 08:07

    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

提交回复
热议问题