[英]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.