Java Constructors - Easy Explanation
What is a Constructor?
----------------------
A constructor is a special method in a class that is automatically called when you create an object of
the class.
Rules of Constructors:
- The constructor name must be the same as the class name.
- Constructors do not have a return type.
- They are used to initialize objects.
Types of Constructors:
----------------------
1. Default Constructor (no parameters)
Example:
class Car {
Car() {
System.out.println("Car is created");
}
public static void main(String[] args) {
Car myCar = new Car();
}
}
Output: Car is created
2. Parameterized Constructor (with parameters)
Example:
class Car {
String model;
Car(String carModel) {
model = carModel;
System.out.println("Car model is: " + model);
}
public static void main(String[] args) {
Car myCar = new Car("BMW");
}
}
Output: Car model is: BMW
3. Constructor Overloading (multiple constructors)
Example:
class Car {
Car() {
System.out.println("Default Car");
}
Car(String model) {
System.out.println("Model: " + model);
}
Car(String model, int year) {
System.out.println("Model: " + model + ", Year: " + year);
}
public static void main(String[] args) {
new Car();
new Car("Audi");
new Car("Mercedes", 2024);
}
}
Output:
Default Car
Model: Audi
Model: Mercedes, Year: 2024
Why use Constructors?
---------------------
- To initialize values at object creation
- To make code cleaner and automatic
- Used heavily in real-world applications