How to call a different constructor conditionally in Java?

后端 未结 5 1529
不思量自难忘°
不思量自难忘° 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:36

    Use static factories, and four private constructors.

    class Foo {
     public static Foo makeFoo(arguments) {
        if (whatever) {
          return new Foo(args1);
        } else if (something else) {
          return new Foo(args2);
        }
        etc...
      }
      private Foo(constructor1) { 
        ...
      }
      ...
    }
    

提交回复
热议问题