Programming with Constructors in Java - Overloading constructors in Java: definition
(Page 4 of 5 )
In my previous articles, I already covered the concept of overloading of methods (or method overloading). If this is a new concept for you, I suggest you refer to my previous articles.
In the previous section, I used a statement something like the following:
MyCalc obj1 = new MyCalc(10,20);
By now you understand that the code snippet above creates an instance/object, calls the constructor which has two parameters, and finally assigns the reference to “obj1.” Let me modify the same like this:
MyCalc obj1 = new MyCalc();
If you execute your program with the above statement, without having a default constructor (covered in first section of this article), it generates a compilation error. That means it could not find any constructor without parameters, and thus it cannot create an instance.
Let me rewrite the class to something like the following:
public class MyCalc {
int x;
int y;
public void setValues(int m, int n) {
x = m;
y = n;
}
public int getSum() {
int z;
z = x + y;
return z;
}
}
Now, the above class doesn’t have any constructor. With it, if you try to execute the following statement again, it will not result in any error.
MyCalc obj1 = new MyCalc();
How is this possible? I didn’t include any default constructor in the above class (nor any other constructor with parameters). That is simply a trick. If a class is not equipped with any constructor, JVM creates one for us (internally) automatically.
Now, let me consider the case of the following two statements:
MyCalc obj1 = new MyCalc();
MyCalc obj2 = new MyCalc(10,20);
Within the above two statements, I am trying to create “obj1,” which tries to call the default constructor (or the constructor which doesn’t have any parameters). I am also trying to create “obj2,” which tries to call the constructor having two parameters.
Can I include two constructors in the same class? Yes. You can have any number of constructors within a single class, but with a difference in parameters. This is called “constructor overloading” (or overloading of constructors).
The next section gives you the full code to demonstrate “constructor overloading.”
Next: Overloading constructors in Java: demo >>
More Java Articles
More By Jagadish Chaterjee