Initializing final fields in Java

后端 未结 4 1872
生来不讨喜
生来不讨喜 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 10:46

    You get this error because if you had called MyClass(SomeType oneIn), two is not initialized.

    0 讨论(0)
  • 2021-02-07 10:54

    You need to make sure that in every constructor you are initializing all final variables. What I would do is have one constructor that initializes all the variables and have all the other constructor call that, passing in null or some default value if there is a field that they are not given a value for.

    Example:

    public class MyClass {
        private final SomeType one;
        private final SuperType two;
    
        //constructor that initializes all variables
        public MyClas(SomeType _one, SuperType _two) {
            one = _one;
            two = _two;
        }
    
        private MyClass(SomeType _one) {
            this(_one, null);
        }
    
        public MyClass(SomeType _one, SubTypeOne _two) {
            this(_one, _two);
        }
    
        public MyClass(SomeType _one, SubTypeTwo _two) {
            this(_one, _two);
        }
    }
    
    0 讨论(0)
  • 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;
        }
    }
    
    0 讨论(0)
  • 2021-02-07 11:10

    All you need to do is ensure that "two" gets initialized. In the first constructor, just add:

    two = null;
    

    unless there's some other value you'd like to give it in the event that only the first constructor is called.

    0 讨论(0)
提交回复
热议问题