A constructor in Java is a special method that is used to initialize objects. The constructor is called when an object of a class is created. It can be used to set initial values for object attributes.
💡 Analogy time: Think of a class like an automobile factory, and objects as the cars rolling off the assembly line. A constructor is the final setup crew at the end of the line. Before a car is handed over to the customer (before your object is ready to be used), the constructor ensures the engine is oiled, the tires are inflated, and the car is painted the correct color. It guarantees the object starts its life in a valid state.
A constructor must have the exact same name as the class, and it cannot have a return type (like void or int).
public class Main {
int x;
// This is the constructor for the Main class
public Main() {
x = 5; // Set the initial value for the class attribute x
}
public static void main(String[] args) {
Main myObj = new Main(); // Create an object of class Main (this will call the constructor)
System.out.println(myObj.x); // Print the value of x
}
}
You might be wondering: "Wait, in previous chapters we created objects with new Car() without ever writing a constructor! How did that work?"
Java has a special rule: If you do not create any constructors for your class, Java automatically provides an invisible, empty default constructor for you. It essentially looks like this: public Car() {}.
However, be careful: The moment you create any custom constructor (like one that requires parameters), Java takes away the free default constructor. If you still want to be able to create an empty object using new Car(), you will have to manually write public Car() {} in your code!
Constructors can also take parameters, which are used to initialize attributes. This is the most common way to create objects with specific initial states.
public class Car {
String modelName;
int modelYear;
// Constructor with parameters
public Car(String name, int year) {
modelName = name;
modelYear = year;
}
public static void main(String[] args) {
Car myCar = new Car("Mustang", 1969);
System.out.println("My car is a " + myCar.modelYear + " " + myCar.modelName);
}
}
Constructors save you a lot of time, as they help you to initialize an object's attributes with just one line of code.
this(...) reduces duplication between constructors. It must be the first statement in the constructor.What must be true about a constructor's name?