This article introduces you to constructors and their uses in Java. It covers the default constructor in Java, handling a constructor with parameters, and constructor overloading.
Programming with Constructors in Java - The default constructor in Java: demo and explanation (Page 2 of 5 )
Until now, in my previous list of articles, I covered only methods. Now, I would like to introduce constructors in Java.
A method which has the same name as a class is nothing but a constructor. It never has any return type. The main use of a constructor is that it is automatically executed by itself, when an object/instance of that specific class is created.
Let us go through the code first. Now, open your previous application (or download it from my previous articles) and open “MyCalc.java.” Modify your code so that it looks something like the following:
public class MyCalc {
int x; int y;
public MyCalc() { x=10; y=10; }
public void setValues(int m, int n) { x = m; y = n; }
public int getSum() { int z; z = x + y; return z; }
}
Now, go back to the frame “test.java.” Double click on it to open, and finally double click on the button to open source view. Within the source view, modify your “buttonActionPerformed” in such a way that it looks like the following:
private void btnShowActionPerformed(java.awt.event.ActionEvent evt) { // TODO add your handling code here: MyCalc obj1 = new MyCalc(); int r; r = obj1.getSum(); this.lblMsg.setText("Sum = " + String.valueOf(r));
}
Once you execute your application and click the button, you should be able to see “Sum=20” as the result. If you examine the testing code above, you will see that I didn’t assign any values to “x” and “y” from “obj1.” They were automatically assigned when the constructor was executed.
In simple terms, the following statement alone creates an instance/object of the class “MyCalc,” executes the constructor, and finally stores the reference of that instance in obj1:
MyCalc obj1 = new MyCalc();
A constructor which has no parameters is called a “default constructor.” The next section will show you an example of working with a constructor with parameters.