簡體   English   中英

在超類/子類框架中使用 ArrayLists

[英]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變量。 相反,請確保soundsParrot中被聲明為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 ,請執行以下操作:
PirateParrotconstructor中初始化並填充sounds ,然后調用超類speak方法。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM