How to call a different constructor conditionally in Java?

后端 未结 5 1537
不思量自难忘°
不思量自难忘° 2020-12-11 16:16

Let\'s say someone gives you a class, Super, with the following constructors:

public class Super
{
    public Super();
    public Super(int arg)         


        
5条回答
  •  盖世英雄少女心
    2020-12-11 16:30

    Can't be done as such as super must be first statement in a constructor.

    The proper alternative is a builder class and to have one constructor in the derived class for each constructor in the super class.

    eg.

    Derived d = new DerivedBuilder().setArg(1).createInstance();
    

    public class DerivedBuilder {
    
        private int arg;
    
        // constructor, getters and setters for all needed parameters
    
        public Derived createInstance() {
            // use appropriate constructor based on parameters
            // calling additional setters if need be
        }
    }
    

提交回复
热议问题