我有一个只有一个子类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
答案 0 :(得分:2)
如果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();
}
答案 1 :(得分:1)
如果您使用包含其超类的数组中的子类,那么您只能访问超类中可用的方法,因为这些是所有子类中常用的方法。
public class Dinosaur
{
private String hobby;
public String getHobby() {
return hobby;
}
...
}
public class Tyrano extends Dinosaur
{
private String teeth;
public String getTeeth() {
return teeth;
}
...
}
然后你有以下
Dinosaur dinosaur = new Tyrano();
String hobby = dinosaur.getHobby(); //this works
String teeth = dinosaur.getTeeth(); //this is compile error!
if(dinosaur instanceof Tyrano) {
Tyrano tyrano = (Tyrano) dinosaur; //casting
teeth = tyrano.getTeeth(); //this works
}
答案 2 :(得分:0)
这是一个典型的错误。关键是,你有一系列没有牙齿或爱好的恐龙,就好像你有一系列人物和其中一个人类#34;是一位老师......不是所有的人都是老师,就像并非恐龙都有牙齿一样。
所以,你需要问你的恐龙"你是Tyrano吗?"如果答案是"是"然后......问他"然后,像Tyrano一样,你的爱好者是什么?"。
让我把它放在代码中:
//are you a Tyrano?
if(Tyrano.class.isAssignableFrom(dinoList[0].getClass())){
// so, I treat you like a Tyrano
Tyrano tyranoDyno= (Tyrano) dinoList[0];
//tell me... teeth and hobbies please?
int teeth = tyranoDyno.getTeeth();
String hobby = tyranoDyno.getHobby();
}
答案 3 :(得分:0)
创建子类时,子类从其超类继承字段和方法。因此,Tyrano
包含Dinosaur
所拥有的所有内容,以及更多内容(teeth
和hobby
)。
你可以创建另一个类,比如说Stego
,它也会扩展Dinosaur
并为armour
添加一个字段。
现在你的恐龙阵列可能包含Tyrano
和Stego
类型(它们都是恐龙,所以这很好)。但是你的程序无法预测它们将成为哪种类型。由于Stego
没有teeth
或hobby
,而Tyrano
没有armour
,因此您无法直接使用这些字段(而是按照Eran的建议)。然而,您可以自由使用Dinosaur
中的所有字段,因为所有恐龙都保证继承这些字段