This article discusses the following topics that concern programming with OOPS (especially single inheritance) in Java using the NetBeans IDE: single inheritance, the role of constructors in a super class, and the role of constructors in a sub class.
Single Inheritance for Classes in Java - An example of single inheritance: explanation (Page 3 of 6 )
This section explains the code listed in the previous section. The class “First” is defined with the following members:
X
Y
setValues
getSum
The class “Second” is defined with the following members:
getProduct
The most important part is the following line of definition for the class “Second”:
public class Second extends First
The above line defines that the class “Second” gets extended (or inherited) from class “First.” That means the class “Second” can be considered a child/sub class. Similarly, the class “First” can be considered a parent/super class.
When a class is inherited from the parent, it will generally contain all the members of its parent class (virtually) within itself. Thus, the class “Second” virtually contains the following members:
X
Y
setValues
getSum
getProduct
You can observe that all the members from its parent class (the class “First”) together with its own individual members, are considered to be the members of class “Second.” All this works behind the screen, magically!
Now, if we proceed to our “test” frame, we have the following initially:
Second obj1 = new Second(); obj1.setValues(10,20);
I declared an object “obj1” of type “Second.” The second statement shows that we are accessing the method “setValues” from the object “obj1.” In fact, physically, the method “setValues” does not present in the class “Second” (or in “obj1”). It is made possible because of inheritance.
We display the sum of two values using the following code fragment:
int r; r = obj1.getSum(); this.lblMsg.setText("Sum = " + String.valueOf(r));
Again you can observe that I am calling the method “getSum,” which is available in the parent class. We display the product of two values using the following code fragment:
r = obj1.getProduct(); this.lblMsg2.setText("Product = " + String.valueOf(r));
Now, you can observe that I am calling the method “getProduct,” which belongs to the class “Second” alone (physically).