Constructors: Special Methods for Object Creation
What you'll learn: How constructors automatically initialize new objects when you create them with the new keyword.
What Is a Constructor?
A constructor is a special method that runs automatically whenever you create a new object using the new keyword. Unlike regular methods, constructors don't have a return type (not even void), and they must have the exact same name as the class.
Think of a constructor like a factory setup process: when you order a new car, the factory doesn't just hand you a shell—it initializes the vehicle with default settings, fuel, and fluids. Similarly, a constructor sets up your object's initial state.
Basic Constructor Syntax
class Car {
String color;
int year;
// Constructor - same name as class, no return type
Car() {
color = "White";
year = 2024;
}
}
// Creating an object invokes the constructor
Car myCar = new Car(); // color is "White", year is 2024
When you write new Car(), Java automatically calls the Car() constructor. The constructor's job is to initialize the object's fields before you start using it.
Why Constructors Matter
Without constructors, you'd have to manually set every field after creating an object. Constructors let you guarantee that objects start in a valid, usable state. They run once per object, at creation time.
If you don't write any constructor, Java provides a default no-argument constructor automatically—but as soon as you write your own, that automatic one disappears.
Key Takeaway: Constructors are special methods with the same name as the class and no return type that automatically initialize objects when created with new.