[英]Using ArrayLists in Superclass/Subclass Framework
我有一個關於在簡單的 inheritance 結構中使用 ArrayLists 等數據結構的問題。 我很難措辭:希望你能理解我想問的問題。
我有一個超類Parrot
和一個擴展Parrot
的子類PirateParrot
。 在Parrot
中,我有以下方法:
public String speak() {
int rand = (int)(Math.random() * sounds.size());
return sounds.get(rand);
}
它返回一個名為sounds
的隨機字符串,該字符串是在Parrot
class 中創建的。
如果我創建一個名為polly
的獨立PirateParrot
實例,它也有自己的 ArrayList,並嘗試調用polly.speak();
PirateParrot
class 中的 speak 方法沒有任何隱式實現,我拋出“線程“主”java.lang.IndexOutOfBoundsException 中的異常:索引:0,大小:0”
如果我專門將Parrot
中的 speak() 方法復制/粘貼到PirateParrot
中,則代碼可以正常編譯並正常運行。 之前到底是什么問題? 有沒有辦法使它正確運行而不必將 speak() 方法復制/粘貼到PirateParrot
? 謝謝!
如果我正確理解了問題,那么最簡單的解決方法就是不在PirateParrot
中聲明另一個sounds
變量。 相反,請確保sounds
在Parrot
中被聲明為protected
,然后在PirateParrot
構造函數中只需使用您希望PirateParrot
具有的任何聲音填充繼承的sounds
變量。
另一種選擇可能是使用getSounds()
方法返回列表並從speak()
內部調用getSounds()
) 而不是直接引用sounds
。 然后PirateParrot
只需要覆蓋getSounds()
來返回它的sounds
版本。
public class Parrot {
private final ArrayList<String> sounds;
private static ArrayList<String> REGULAR_PARROT_SOUNDS = new ArrayList<String>();
static {
REGULAR_PARROT_SOUNDS.add(...);
...
}
protected Parrot(ArrayList<String> sounds) {
this.sounds = sounds;
}
public Parrot() {
this(REGULAR_PARROT_SOUNDS);
}
}
public class PirateParrot {
private static ArrayList<String> PIRATE_PARROT_SOUNDS = ...;
public PirateParrot() {
super(PIRATE_PARROT_SOUNDS);
}
}
在調用它之前,您沒有初始化和填充sounds
,請執行以下操作:
在PirateParrot
的constructor
中初始化並填充sounds
,然后調用超類的speak
方法。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.