如何在Java中有条件地调用不同的构造函数?

发布于 2025-01-04 11:59:57 字数 627 浏览 0 评论 0原文

假设有人为您提供了一个带有以下构造函数的类 Super

public class Super
{
    public Super();
    public Super(int arg);
    public Super(String arg);
    public Super(int[] arg);
}

假设您想要创建一个子类 Derived。如何有条件地调用 Super 中的构造函数?

换句话说,让这样的事情发挥作用的“正确”方法是什么?

public class Derived extends Super
{
    public Derived(int arg)
    {
        if (some_condition_1)
            super();
        else if (some_condition_2)
            super("Hi!");
        else if (some_condition_3)
            super(new int[] { 5 });
        else
            super(arg);
    }
}

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

public class Super
{
    public Super();
    public Super(int arg);
    public Super(String arg);
    public Super(int[] arg);
}

And let's say you want to create a subclass Derived. How do you conditionally call a constructor in Super?

In other words, what is the "proper" way to make something like this work?

public class Derived extends Super
{
    public Derived(int arg)
    {
        if (some_condition_1)
            super();
        else if (some_condition_2)
            super("Hi!");
        else if (some_condition_3)
            super(new int[] { 5 });
        else
            super(arg);
    }
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

深爱成瘾 2025-01-11 11:59:57

使用静态工厂和四个私有构造函数。

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) { 
    ...
  }
  ...
}

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) { 
    ...
  }
  ...
}
似梦非梦 2025-01-11 11:59:57

是的,@Johan Sjöberg 说的。

看起来你的例子也是高度人为的。没有神奇的答案可以清除这个混乱:)

通常,如果你有这么多构造函数,最好将它们重构为四个单独的类(一个类应该只负责一种类型的事情)。

Yeah, what @Johan Sjöberg said.

Also looks like your example is highly contrived. There's no magical answer which would clear this mess :)

Usually, if you have such a bunch of constructors it would be a good idea to refactor them as four separate classes (a class should be only responsible for one type of thing).

断爱 2025-01-11 11:59:57

super 必须是构造函数中的第一个语句,因此示例中的逻辑无效。

正确的方法是在扩展类中创建相同 4 个构造函数。如果您需要验证逻辑,您可以使用例如builder模式。您还可以按照 @davidfrancis 的评论中的建议将所有构造设为私有并提供静态工厂方法。例如,

public static Derived newInstance(int arg) {
      if (some condition) {
         return new Derived(arg);
      }
      // etc
}

super must be the first statement in a constructor, hence the logic in your sample is not valid.

The proper way is to create the same 4 constructors in your extending class. If you need validation logic you can use e.g., the builder pattern. You can also as suggested in the comments by @davidfrancis make all constructs private and supply a static factory method. E.g.,

public static Derived newInstance(int arg) {
      if (some condition) {
         return new Derived(arg);
      }
      // etc
}
錯遇了你 2025-01-11 11:59:57

您不能这样做,但您可以从调用您的类的代码中执行此操作:

        if (some_condition_1)
            new Super();
        else if (some_condition_2)
            new Super("Hi!");
        else if (some_condition_3)
            new Super(new int[] { 5 });
        else
            new Super(arg);

You can't do that, but you can do this from the code that calls your class:

        if (some_condition_1)
            new Super();
        else if (some_condition_2)
            new Super("Hi!");
        else if (some_condition_3)
            new Super(new int[] { 5 });
        else
            new Super(arg);
深海不蓝 2025-01-11 11:59:57

不能这样做,因为 super 必须是构造函数中的第一个语句。

正确的替代方案是一个构建器类,并在派生类中为超类中的每个构造函数提供一个构造函数。

例如。

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
    }
}

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
    }
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文