我有一个只有一个子类Dinosaur
的超类Tyrano
我具有这些属性的Dinosaur
:
public Dinosaur(String name, String size, String movement, String diet, String terainType){
...
//i've already made the setters and getters along with some helper functions
}
我有
Tyrano
以及2个其他属性,分别是teeth
和hobby
public Tyrano(String name, String size, String movement, String diet, String terainType, int teeth, String hobby){
...
//made setters and getters with some helper functions
}
现在在我的驱动程序中,我想创建一个数组类型
Dinosaur
,它将接受多个Dinosaur
子类,其中一个是Tyrano
子类,我不知道是否可能,但我的讲师说是这样,我做了什么,这主要是:Dinosaur[] dinoList = new Dinosaur[9];
dinoList[0] = new Tyrano("Gary", "Large", "other dino Meat", "Land", 30, "singing");
int teeth = dinoList[0].getTeeth();
String hobby = dinoList[0].getHobby();
...//i also called the helper functions that were in Tyrano
它得到一个错误:
error: cannot find symbol
dinoList[0].getTeeth();
^
error: cannot find symbol
dinoList[0].getHobby();
^
...//along with same errors with the helper functions that were in Tyrano
...//it also happens when i call setters that were unique for the subclass Tyrano
而且我不知道为什么要这样做,我已经仔细检查过并且没有语法错误,并且已经定义了辅助函数,还有那些getter和setter,但是对于常见的辅助函数没有问题。超类
Dinosaur
最佳答案
如果getTeeth()
类不存在getHobby()
和Dinosaur
,则不能从对Dinosaur
的引用中调用它们。即使存储在dinoList[0]
中的实际实例是Tyrano
,也不能在不将引用转换为Tyrano
的情况下访问其唯一方法。
这将起作用:
if (dinoList[0] instanceof Tyrano) {
Tyrano t = (Tyrano) dinoList[0];
int teeth = t.getTeeth();
String hobby = t.getHobby();
}