[!NOTE] When you use the
newkeyword, Java executes a special method called a Constructor right as the object is being built. This is your opportunity to force required parameters upon creation.
The Constructor Method
A constructor is a highly specialized method that serves exactly one purpose: initializing the state of a new object.
Rules of a Constructor:
- Its name must exactly match the Class name.
- It cannot have a return type (not even
void). - It is called automatically the moment
newis executed.
public class Car {
String modelName;
int manufacturingYear;
// This is the Constructor!
public Car(String name, int year) {
modelName = name;
manufacturingYear = year;
System.out.println("A new " + name + " has rolled off the assembly line.");
}
public static void main(String[] args) {
// You MUST provide the parameters when calling 'new'!
Car myCar = new Car("Mustang", 1969);
}
}
Constructor Overloading
What if you want to give developers multiple ways to build an object? Maybe occasionally they know the manufacturing year, but sometimes they just want a default "Blank" car?
You can overload constructors by writing multiple constructors with different parameter signatures. The JVM will automatically figure out which one you are trying to use based on the arguments you pass.
public class User {
String email;
String role;
// Constructor 1: Fully custom
public User(String emailArg, String roleArg) {
email = emailArg;
role = roleArg;
}
// Constructor 2: Assumes a default 'guest' role!
public User(String emailArg) {
email = emailArg;
role = "guest";
}
public static void main(String[] args) {
User admin = new User("admin@site.com", "admin_role"); // Calls Constructor 1
User random = new User("rando@site.com"); // Calls Constructor 2
}
}
[!CAUTION] If you do not write a single constructor in your class, Java secretly compiles an invisible, empty "Default Constructor" for you so
new Car()works. However, the moment you explicitly write any parameterized constructor, the invisible default one is destroyed! You must manually re-add an emptypublic Car() {}if you want it back.