Array of type Grandparent can't access elements from Grandchild

50 Views Asked by At

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!

2

There are 2 best solutions below

4
markspace On

Another way to look at this is if you don't want this behavior, don't re-declare the field. In other words, adding String declares 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.

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"; }
}

This will print "Red Bird".

0
Ozgun On
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);
    }
}