Best way to handle multiple constructors in Java

后端 未结 9 1453
没有蜡笔的小新
没有蜡笔的小新 2020-12-02 07:00

I\'ve been wondering what the best (i.e. cleanest/safest/most efficient) way of handling multiple constructors in Java is? Especially when in one or more constructors not al

9条回答
  •  死守一世寂寞
    2020-12-02 07:59

    You should always construct a valid and legitimate object; and if you can't using constructor parms, you should use a builder object to create one, only releasing the object from the builder when the object is complete.

    On the question of constructor use: I always try to have one base constructor that all others defer to, chaining through with "omitted" parameters to the next logical constructor and ending at the base constructor. So:

    class SomeClass
    {
    SomeClass() {
        this("DefaultA");
        }
    
    SomeClass(String a) {
        this(a,"DefaultB");
        }
    
    SomeClass(String a, String b) {
        myA=a;
        myB=b;
        }
    ...
    }
    

    If this is not possible, then I try to have an private init() method that all constructors defer to.

    And keep the number of constructors and parameters small - a max of 5 of each as a guideline.

提交回复
热议问题