Home > front end >  Array of type Grandparent can't access elements from Grandchild
Array of type Grandparent can't access elements from Grandchild

Time:09-23

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!

CodePudding user response:

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 removing makes the type system re-use the name you declared before.

public class Animal {
  String name = "Animal";
}

public class Bird extends Animal {
  name = "Bird";
}

public class RedBird extends Bird {
  name = "Red Bird";
}

This should print "Red Bird", though I didn't test it.

CodePudding user response:

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);
    }
}
  • Related