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 - The role of the default constructor in the super class during single inheritance (Page 4 of 6 )
The previous two sections explained the concept of single inheritance with a simple example. My previous article introduced constructors in Java. Constructors do play major role in inheritance. Let us start our discussion with a simple default constructor in the super class.
Modify your code in “first.java” as follows:
public class First {
int x=0; int y=0;
/** Creates a new instance of First */ public First() { x = 10; y = 20; }
public void setValues(int m, int n) { x = m; y = n; }
public int getSum() { int t; t = x + y; return t; } }
Update your code in “test.java” as follows:
private void btnShowActionPerformed(java.awt.event.ActionEvent evt) { // TODO add your handling code here: Second obj1 = new Second(); int r; r = obj1.getSum(); this.lblMsg.setText("Sum = " + String.valueOf(r)); r = obj1.getProduct(); this.lblMsg2.setText("Product = " + String.valueOf(r));
}
From the code fragments above, you can observe that I am assigning the values of members directly within the constructor of the super class (“First”). Within the “test.java,” I removed the assigning of values through the method “setValues.”
Once you execute your program, you will see the same output. From this concept, you can conclude that the default constructor of a super class is automatically executed when you create the instance of a sub class. The case would be a bit different if you have constructors with parameters or constructor overloading. We shall look into that later.