我想创建一个可以为每个参数接受两种不同数据类型的类。如何实现这一目标?
我意识到下面的代码不起作用,但我怎么能做出类似的工作呢?基本上这样参数可以是int或String或类似的东西吗?
示例:
public Combat(int attack || String attack, int defence || String defence) {
//code to parse strings into ints
}
答案 0 :(得分:3)
您似乎想要提供overloaded constructor。您可以使用类似
的方式委托int
版本
private int attack;
private int defence;
public Combat(int attack, int defence) {
this.attack = attack;
this.defence = defence;
}
public Combat(String attack, String defence) {
this(Integer.parseInt(attack), Integer.parseInt(defence));
}
如果您想传递String, int
或int, String
public Combat(int attack, String defence) {
this(attack, Integer.parseInt(defence));
}
public Combat(String attack, int defence) {
this(Integer.parseInt(attack), defence);
}
答案 1 :(得分:1)
您应该创建2个构造函数。我将在下面举一个例子:
public Test(String test){
// blah blah blah
}
public Test(int test){
// blah blah blah
}
因此,在创建实例时,它可以使用任一参数。
另外,不要对catch语句感到困惑。捕获可以使用一个|,例如:
来实现多个异常try{
// blah blah blah
}
catch(TestException | TestExceptionTwo e){
// blah blah blah
}
使用单个|不与构造函数或方法一起工作。