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

在Java中,子类如何根据条件调用超类的不同构造器?博客讨论了一个示例,展示如何在Derived类中依据不同条件使用Super类的多个构造器。通常,如果有大量构造器,建议进行重构,每个类专注于一种特定类型的操作。
摘要由CSDN通过智能技术生成

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

}

}

解决方案

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值