🧱 What is a Constructor?
A constructor in Java is a special block of code that's called when an object is created. It’s used to initialize the object with default or user-defined values.
Syntax:
ClassName() {
// initialization code
}
It must have the same name as the class and no return type—not even void.
🎯 Why Use Constructors?
Imagine you're creating a blueprint (class) for a car. When you make a new car object, you’ll want to set the car’s brand, model, and year. That’s where constructors come in—they let you prefill those details during object creation.
🛠️ Types of Constructors in Java
Java gives you flexibility with different types of constructors.
1. Default Constructor
This is the no-argument constructor Java provides automatically if you don’t define any constructor yourself.
EXAMPLE:
class Car {
Car() {
System.out.println("Car is created");
}
}
Usage:
Car myCar = new Car(); // Output: Car is created
2. Parameterized Constructor
You define this to pass values during object creation.
example:
class Car {
String brand;
Car(String b) {
brand = b;
}
}
Usage:
Car myCar = new Car("Toyota");
System.out.println(myCar.brand); // Output: Toyota
📏 Constructor Rules to Keep in Mind
- No return type – Not even void.
- Must match class name exactly.
- You can overload constructors – Create multiple versions with different parameters.
- If you define any constructor, Java won’t give you a default one.
👀 Constructor Overloading Example
`class Car {
String brand;
int year;
Car() {
brand = "Unknown";
year = 0;
}
Car(String b, int y) {
brand = b;
year = y;
}
}
`
Usage:
`Car car1 = new Car();
Car car2 = new Car("Honda", 2022);
System.out.println(car1.brand); // Unknown
System.out.println(car2.brand); // Honda
`