![]() |
VOOZH | about |
Java supports constructor overloading, which allows a class to have more than one constructor with different parameter lists. The appropriate constructor is selected at compile time based on the arguments passed during object creation. Constructor overloading enables objects to be initialized in multiple ways, improving flexibility and code clarity.
Constructor overloading is useful when:
Example:
The Thread class provides multiple constructors. For example:
Thread t = new Thread("MyThread");
If no arguments are required, the default constructor can be used. If a thread name is needed, a parameterized constructor is selected automatically.
Consider a class Box with only one constructor:
In this case, the following statement is invalid:
Box box = new Box(); // Compile-time error
The class does not support creating:
By adding multiple constructors, different initialization options become available.
Volume of mybox1: 3000.0 Volume of mybox2: 0.0 Volume of mycube: 343.0
The this() keyword is used to call one constructor from another constructor in the same class. It helps avoid code duplication and ensures consistent initialization.
0.0
Invalid Example:
Box(int num) {
boxNo = num;
this(); // Compile-time error
}
Note:
- Constructors can be overloaded like methods, but they do not have return types.
- If any constructor is defined, Java does not generate a default constructor.
- Constructor overloading improves object initialization flexibility.
- Overloading is resolved at compile time.
Feature | Constructor Overloading | Method Overloading |
|---|---|---|
Purpose | Initialize objects | Define multiple behaviors |
Return type | Not allowed | Required |
Name | Same as class | Any valid method name |
Invocation | new keyword | Method call |