What is a Constructor in Java?
A constructor is a special method that is used to initialize objects in Java. It has the same name as the class and does not have a return type—not even void
.
Key Points:
- Called automatically when an object is created.
- Can be overloaded (just like methods).
- Used to assign initial values to object properties.
Syntax Example:
class Car {
String model;
// Constructor
Car(String m) {
model = m;
}
}
In the above example, when you create a Car
object with new Car("Toyota")
, the constructor sets the model.
What is Method Overloading?
Method overloading allows a class to have more than one method with the same name, but different parameter lists (type or number of parameters).
Key Points:
- Increases readability of the program.
- Compiler determines which method to call based on arguments.
- Return type can be different, but it’s not enough to overload a method just by changing the return type.
Example:
class Calculator {
int add(int a, int b) {
return a + b;
}
double add(double a, double b) {
return a + b;
}
int add(int a, int b, int c) {
return a + b + c;
}
}
Here, the method add
is overloaded three times with different parameter combinations.
Constructor Overloading
Just like methods, constructors can also be overloaded to provide different ways to initialize an object.
Example:
class Student {
String name;
int age;
Student() {
name = "Unknown";
age = 0;
}
Student(String n, int a) {
name = n;
age = a;
}
}
This allows flexibility: you can create a student with default values or provide specific values.
Official Java Reference
For more detailed information, always refer to the official Java documentation:
Top comments (0)