A Constructor is a special method that is called automatically the very moment you use the keyword new to create an object. Its primary job is to initialize the object—setting up the starting values for its variables so the object is ready to use immediately.
Think of it like a "Startup Sequence" for your code.
Rules of Constructors:
Same Name: The constructor MUST have the exact same name as the Class.
No Return Type: It doesn't even use
void. It has no return type at all.Automatic: You never call it manually (like
myCar.Constructor()); it runs automatically duringnew Car().
The this Keyword
Inside a constructor, you'll often see the word this. Because the parameter names (the inputs) are often the same as the class variables, this.brand tells Java: "I mean the variable belonging to this specific object, not the temporary input variable."
The Code Example:
class SmartPhone {
String model;
int storage;
double price;
// 1. The Constructor
// It takes inputs and assigns them to the object's fields immediately
public SmartPhone(String model, int storage, double price) {
this.model = model; // "this.model" is the field, "model" is the input
this.storage = storage;
this.price = price;
System.out.println("Building a new " + model + "...");
}
// A method to show the specs
void showSpecs() {
System.out.println("Model: " + model);
System.out.println("Storage: " + storage + "GB");
System.out.println("Price: $" + price);
System.out.println("----------------------");
}
}
public class Main {
public static void main(String[] args) {
// Now we can create and initialize objects in ONE line!
SmartPhone phone1 = new SmartPhone("iPhone 15", 128, 799.99);
SmartPhone phone2 = new SmartPhone("Galaxy S24", 256, 899.99);
// Displaying the data
phone1.showSpecs();
phone2.showSpecs();
}
}Expected Output:
Building a new iPhone 15...
Building a new Galaxy S24...
Model: iPhone 15
Storage: 128GB
Price: $799.99
----------------------
Model: Galaxy S24
Storage: 256GB
Price: $899.99
----------------------Constructors ensure that your objects are never "broken" or empty. Without a constructor, you might forget to give a Usera username, which could crash your app later. By requiring those details in the constructor, you force the program to be valid from the moment of "birth."
Fun Fact: If you don't write a constructor, Java secretly creates a "Default Constructor" for you that does nothing. But once you write your own, the default one disappears!