I've created an array with a grandparent type, passed objects that are grandchildren of that type, but I can't access the elements from the child class. These aren't the exact things I'm coding they are just examples.
Here is the Grandparent
public class Animal {
String name = "Animal";
}
Here is the child class
public class Bird extends Animal {
String name = "Bird";
}
Here is the Grandchild class
public class RedBird extends Bird {
String name = "Red Bird";
}
The problem I am encountering is this
public class Room {
public static void main(String args[]) {
Animal[] anim = {new RedBird};
System.out.println(Animal[0].name);
}
}
The program will output the wrong thing
Animal
Does anybody know how I can fix this? Thanks!
Another way to look at this is if you don't want this behavior, don't re-declare the field. In other words, adding
Stringdeclares a new field, and you don't want to do that. You can use an initializer block or a constructor to assign a new name.This will print "Red Bird".