Call a method after the constructor has ended

前端 未结 7 783
迷失自我
迷失自我 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:02

    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.

提交回复
热议问题