In this article, I shall provide an introduction to multi-level inheritance when programming with OOPS in Java using NetBeans IDE. I will also cover calling methods of the super class, and discuss a simple, practical example.
Multi Level Class Inheritance in Java - An example of multi-level inheritance: explanation (Page 3 of 5 )
This section will explain the coding listed in the previous sections. The class “First” is defined with the following members:
X
Y
setValues
getSum
The class “Second” is defined with the following member:
getProduct
As the class “Second” is inherited from “First,” it virtually contains the following members:
X
Y
setValues
getSum
getProduct
Now the class “Third” is inherited from “Second.” Thus, it virtually contains the following members:
X
Y
setValues
getSum
getProduct
getDifference
You can observe that all the members from the parent class (class “Second”) and grand parent class (class “First”), along with its own individual members are considered to be the members of the class “Third.” All this works behind the screen, magically!
Now, if we proceed to our “test” frame, we have the following initially:
Third obj1 = new Third();
I declared an object “obj1” of type “Third.”
We display the difference of two values using the following code fragment:
int r; r = obj1.getDifference();
You can observe that I am calling the method “getDifference” without assigning any values to “x” and “y.” When the object of the class “Third” is created, the constructor of class “First” is executed followed by the class “Second.” So “x” and “y” are automatically assigned the values of 90 and 80 respectively. We display the difference of the two values using the following code fragment: