I have created the following puzzle for inheritance in Java:
Animal.java
public class Animal {
private String sound;
public void roar() {
System.out.println(sound);
}
public void setSound(String sound) {
this.sound = sound;
}
}
Tiger.java
public class Tiger extends Animal {
public String sound;
public Tiger() {
sound = "ROAR";
}
}
Jungle.java
public class Jungle {
public static void main(String[] args) {
Tiger diego = new Tiger();
diego.roar();
diego.sound = "Hust hust";
diego.roar();
diego.setSound("bla");
diego.roar();
System.out.println(diego.sound);
}
}
Output:
null
null
bla
Hust hust
I guess this weird behaviour is taking place, because sound in Animal is private while sound in Tiger is public. But can you explain (and tell me the relevant parts of the JLS) why this happens?
Fields are not polymorphic, methods are polymorphic.
calls
roar()method inAnimaland printssoundfromAnimal.Sets sound value in
Tigerclasssoundvariablereturns null; because prints sound from Animal, which is still null. Above sound assignment reflects on Tiger class variable, not Animal class.
diego.setSound(“bla”);
sets
Animalsound toblaprints
blabecause setSound update sound variable of Animal class withbla.System.out.println(diego.sound);
prints
Hust hustdue to the fact that diego is of typeTigerand you have accessed field sound ofTigerand fields are not polymorphic.Please refer java language specification 8.3 for more details.