我创建了一个具有祖父母类型的数组,传递的对象是该类型的孙辈,但无法访问子类中的元素。这些不是我正在编写的东西,它们只是例子。
这是爷爷奶奶
public class Animal {
String name = "Animal";
}这是孩子的课
public class Bird extends Animal {
String name = "Bird";
}这是孙子班
public class RedBird extends Bird {
String name = "Red Bird";
}我遇到的问题是
public class Room {
public static void main(String args[]) {
Animal[] anim = {new RedBird};
System.out.println(Animal[0].name);
}
}这个程序会输出错误的东西
Animal有人知道我怎么解决这个问题吗?谢谢!
发布于 2022-09-22 23:46:30
另一种看待这个问题的方法是,如果不想要这种行为,就不要重新声明字段。换句话说,添加String声明了一个新字段,您不想这样做。您可以使用初始化器块或构造函数来分配新名称。
public class Animal {
String name = "Animal";
}
public class Bird extends Animal {
{ name = "Bird"; } // This is an initializer block
}
public class RedBird extends Bird {
{ name = "Red Bird"; }
}这将印上“红鸟”。
发布于 2022-09-23 00:18:55
class Animal {
String name;
public Animal() {
name = "Animal";
}
}
class Bird extends Animal {
public Bird() {
name = "Bird";
}
}
class RedBird extends Bird {
public RedBird() {
name = "RedBird";
}
}
class Main {
public static void main(String[] args) {
Animal a = new RedBird();
System.out.println(a.name);
}
}https://stackoverflow.com/questions/73821511
复制相似问题