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?
Inheritance is a mechanism in which one class acquires the property of another class. For example, a child inherits the traits of his/her parents. With inheritance, we can reuse the fields and methods of the existing class. Hence, inheritance facilitates Reusability and is an important concept of OOPs.
In Java, it is possible to inherit attributes and methods from one class to another. We group the "inheritance concept" into two categories: subclass (child) - the class that inherits from another class. superclass (parent) - the class being inherited from.
Multilevel Inheritance occurs when a class extends a class that extends another class. For example, class C extends class B, and class B extends class A. This is referred to as multilevel Inheritance.
Fields are not polymorphic, methods are polymorphic.
diego.roar();
calls roar()
method in Animal
and prints sound
from Animal
.
diego.sound = "Hust hust";
Sets sound value in Tiger
class sound
variable
diego.roar();
returns 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 Animal
sound to bla
diego.roar();
prints bla
because setSound update sound variable of Animal class with bla
.
System.out.println(diego.sound);
prints Hust hust
due to the fact that diego is of type Tiger
and you have accessed field sound of Tiger
and fields are not polymorphic.
Please refer java language specification 8.3 for more details.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With