[英]A class that accepts two different data types in Java?
我想創建一個可以為每個參數接受兩種不同數據類型的類。 如何做到這一點?
我意識到下面的代碼不起作用,但我怎樣才能使類似的工作? 基本上,該參數可以是 int 或 String 或類似的東西?
例子:
public Combat(int attack || String attack, int defence || String defence) {
//code to parse strings into ints
}
看來您想提供一個重載的構造函數。 你可以用類似的東西委托給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);
}
您應該創建 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
}
使用單個 | 不適用於構造函數或方法。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.