Initializing final fields in Java

后端 未结 4 1928
生来不讨喜
生来不讨喜 2021-02-07 10:12

I have a class with lots of final members which can be instantiated using one of two constructors. The constructors share some code, which is stored in a third constructor.

4条回答
  •  天命终不由人
    2021-02-07 11:01

    How about this? (Updated for changed question)

    public class MyClass {
    
        private final SomeType one;
        private final SuperType two;
    
        public MyClass (SomeType commonArg, int intIn) {
            this(commonArg, new SubTypeOne(intIn));
        }
    
        public MyClass (SomeType commonArg, String stringIn) {
            this(commonArg, new SubTypeTwo(stringIn));
        }
    
        private MyClass (SomeType commonArg, SuperType twoIn) {
            one = commonArg;
            two = twoIn;
        }
    }
    

提交回复
热议问题