我有一个关于在简单继承结构中使用ArrayLists等数据结构的问题。我很难措辞:希望你能理解我想问的问题。
我有一个父类(super class) Parrot
和一个扩展 Parrot
的子类 PirateParrot
。在 Parrot
中,我有以下方法:
public String speak() {
int rand = (int)(Math.random() * sounds.size());
return sounds.get(rand);
}
它返回一个名为 sounds
的 ArrayList 中的随机字符串,它是在 Parrot
类中创建的。
如果我创建一个名为 polly
的 PirateParrot
实例,它也有自己的 ArrayList,并尝试调用 polly.speak();
没有对 PirateParrot
类中的 speak 方法进行任何隐式实现,我被抛出 "Exception in thread "main"java.lang.IndexOutOfBoundsException: Index: 0, Size: 0"
如果我专门将 Parrot
中的 speak() 方法复制/粘贴到 PirateParrot
中,代码可以正常编译并正常运行。之前到底是什么问题?有没有一种方法可以使它正确运行而不必将 speak() 方法复制/粘贴到 PirateParrot
中?谢谢!
最佳答案
如果我正确理解了问题,那么最简单的解决方法就是不在 PirateParrot
中声明另一个 sounds
变量。相反,确保 sounds
在 Parrot
中声明为 protected
,然后在 PirateParrot
构造函数中只填充继承的 sounds
变量,包含您希望 PirateParrot
拥有的任何声音。
另一种选择可能是使用 getSounds()
方法返回列表并从 speak()
内部调用 getSounds()
而不是直接引用 sounds
。然后 PirateParrot
只需重写 getSounds()
即可返回它的 sounds
版本。
关于java - 在父类(super class)/子类框架中使用 ArrayLists,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10100416/