如何在Java中有条件地调用不同的构造函数? [英] How to call a different constructor conditionally in Java?

查看:255
本文介绍了如何在Java中有条件地调用不同的构造函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设有人给你一个类 Super ,其中包含以下构造函数:

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

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

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


推荐答案

,什么@JohanSjö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).

这篇关于如何在Java中有条件地调用不同的构造函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆