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.