In Java, a constructor is a special block of code used to initialize objects when they are created. Think of it as the blueprint that sets up your object’s initial state.
🔧 Key Uses of a Constructor:
- Initialize object properties: It sets default or custom values to the fields of a class.
- Automatically called: When you create an object using
new
, the constructor is invoked without needing to call it explicitly. - Supports overloading: You can define multiple constructors with different parameters to allow flexible object creation.
🧪 Example:
public class Car {
String model;
int year;
// Constructor
public Car(String m, int y) {
model = m;
year = y;
}
public static void main(String[] args) {
Car myCar = new Car("Mustang", 1969);
System.out.println(myCar.model + " - " + myCar.year);
}
}
This will output: Mustang - 1969