Constructors
Overview
A Constructor is a special setup method. It is called exactly once, at the exact moment an object is created (using the `new` keyword).
If a Class is a blueprint for a house, the constructor is the construction crew. Before anyone is allowed to move into the house, the crew must install the plumbing and electricity. A constructor's job is to initialize the object's variables to a valid starting state.
1. The Rules of Constructors
Constructors have two strict rules: They must have the EXACT same name as the Class, and they do NOT have a return type (not even `void`).
2. The Default Constructor
If you don't write a constructor, Java secretly provides an empty 'default' constructor for you. But if you write your own, Java takes the default one away.
3. Parameterized Constructors
You can pass data into a constructor so the object is created with specific details right from the start (like ordering a pizza and specifying the toppings immediately).
Syntax
Here we force the creator of a Student object to provide a name immediately.
public class Student {
String name;
int age;
// Parameterized Constructor
public Student(String studentName, int studentAge) {
name = studentName;
age = studentAge;
}
}
public class Main {
public static void main(String[] args) {
// We MUST provide the name and age to build the object
Student s1 = new Student("Alice", 20);
System.out.println(s1.name + " is " + s1.age);
}
}Common Pitfalls
- Accidentally putting `void` in front of a constructor (e.g., `public void Student()`). Java will think it's a normal method, not a constructor, causing huge bugs.
Interview Tips
- Constructor Overloading: You can have multiple constructors in one class, as long as they take different parameters. This is highly tested in interviews.
Real-World Example
Constructors are used to ensure an object is never created in a 'broken' or invalid state.
public class BankAccount {
String owner;
double balance;
// You cannot open a bank account without an owner!
public BankAccount(String ownerName) {
owner = ownerName;
balance = 0.0; // Starting balance is always 0
}
}