Constructors
Overview
A Constructor is a special method inside a class that is automatically invoked the exact moment an Object is created using the new keyword. Its primary responsibility is to initialize the object's starting state (e.g., setting default values for variables) before the object is ever used by the rest of the application.
Constructors have two strict rules that differentiate them from normal methods:
1. Exact Name Match: The constructor's name must perfectly match the Class name, including capitalization.
2. No Return Type: Unlike standard methods, constructors do NOT have a return type (not even void).
If you do not write a constructor, the Java compiler silently inserts a 'Default Constructor' (an empty constructor with no parameters) behind the scenes, ensuring the object can still be created.
Syntax
Constructors guarantee that an object is born into a valid state. By forcing the admin creation to pass a username, it prevents the existence of a User object without a name.
public class User {
String username;
boolean isActive;
// 1. Parameterized Constructor
// Forces you to provide a username when creating the object!
public User(String username) {
this.username = username;
this.isActive = true; // Sets default state automatically
System.out.println("User " + username + " created!");
}
// 2. Default/No-Arg Constructor (Overloaded)
public User() {
this.username = "Guest";
this.isActive = false;
}
}
public class Main {
public static void main(String[] args) {
// Triggers the parameterized constructor
User admin = new User("admin123");
// Triggers the no-arg constructor
User guest = new User();
}
}Common Pitfalls
- Accidentally adding a return type. If you write
public void User() { ... }, the compiler no longer treats it as a Constructor! It treats it as a regular method that just happens to be named 'User'. The actual constructor will remain the invisible default one, causing massive initialization bugs. - Losing the Default Constructor. If you manually write a Parameterized Constructor (e.g.,
public User(String name)), Java immediately deletes the invisible Default Constructor. If other parts of your code were relying onnew User(), they will instantly break unless you manually write out an emptypublic User() {}constructor.
Interview Questions
private?Yes! If you mark a constructor as private, no other class can instantiate this object using the new keyword. This is the foundational technique used to build the 'Singleton' Design Pattern, ensuring only one instance of a class ever exists in the entire application.
While it does not have an explicit return type in its signature, a Constructor implicitly returns the memory reference address of the newly constructed object back to the caller.
Real-World Example
Database Connection objects absolutely require credentials (URL, username, password) to function. Developers use Parameterized Constructors to force whoever is creating the Connection object to provide those credentials immediately, preventing the creation of a 'dead' or useless connection object.
public class DatabaseConnection {
private String url;
// Constructor strictly forces validation at birth
public DatabaseConnection(String dbUrl) {
if(dbUrl == null || !dbUrl.startsWith("jdbc:")) {
throw new IllegalArgumentException("Invalid URL");
}
this.url = dbUrl;
}
}Check Your Knowledge
Test your understanding of Constructors with these quick questions.