0

I have some (comprehension-) issues with inheritance and static variables in java.

Let's say I have three classes with a same static variable and inheritance among each other:

public class Animal {
    public static final String DEFAULT_NAME = "anymal";
}
public class Dog extends Animal {
    public static final String DEFAULT_NAME = "doggy";
}
public class Cat extends Animal {
    public static final String DEFAULT_NAME = "caddy";
}

Now i have a list with with animals as well as cats and dogs. And i want to print their DEFAULT_NAME:

public class Main {

    public static void main(String[] args) {
        List<Animal> animals = new ArrayList<>();
        animals.add(new Dog());
        animals.add(new Cat());
        animals.add(new Animal());
        
        
        for (Animal animal : animals) {
            System.out.println(animal.DEFAULT_NAME);
        }
    }
}

What i need is:

doggy
caddy
anymal

but what I get is:

anymal
anymal
anymal

I am not really sure, but I think the Serializable-Interface is working as needed, but no have idea how it is built. At least the fact that my IDE is reminding me, that my child class should have a static variable is a good approach.

Stephen C
  • 698,415
  • 94
  • 811
  • 1,216
Leo
  • 36
  • 2
  • What does Serializable have to do with anything? – Mad Physicist Aug 24 '21 at 05:25
  • If i use `java.io.Serializable`, i am forced to declare the `serialVersionUID`. This feels similar to my problem. But as i said: I am not really sure. – Leo Aug 24 '21 at 05:28
  • You will get what you want if you use a non-static method. It seems like it should be a static method or property but only non-static methods have polymorphism. [example](https://ideone.com/cnShak). – Paul Rooney Aug 24 '21 at 05:31
  • Well this is a mini-example. In my real code, i need static variables indeed. – Leo Aug 24 '21 at 05:39

0 Answers0