Java Constructors
A constructor is a special method that runs automatically the moment you create an object. Its job is to set up the object with sensible starting values so it is ready to use right away.
What is a constructor?
In Java, a constructor looks a bit like a method, but with two important differences: it has the exact same name as the class, and it has no return type (not even void). Whenever you use the new keyword, Java calls the matching constructor for you. This is where you give your object its initial state.
- The constructor name must match the class name, letter for letter.
- A constructor never declares a return type.
- It is triggered automatically by the new keyword.
- If you write no constructor at all, Java quietly supplies an empty default one.
A simple constructor
public class Car {
int speed; // a field
// Constructor: same name as the class, no return type
public Car() {
speed = 40; // set a starting value
}
public static void main(String[] args) {
Car myCar = new Car(); // constructor runs here
System.out.println(myCar.speed); // Outputs 40
}
}Constructors become far more useful when they accept parameters. This lets you pass in different values each time you create an object, so every object can start life with its own data instead of a single hard-coded value.
A constructor with parameters
public class Car {
String model;
int year;
// Parameters let each Car start with its own values
public Car(String model, int year) {
this.model = model; // 'this' points to the current object's field
this.year = year;
}
public static void main(String[] args) {
Car a = new Car("Tesla", 2024);
Car b = new Car("Toyota", 2021);
System.out.println(a.model + " " + a.year); // Tesla 2024
System.out.println(b.model + " " + b.year); // Toyota 2021
}
}You can define more than one constructor in the same class, as long as each version takes a different list of parameters. This is called constructor overloading, and it gives callers several convenient ways to create an object.
Exercise: Java Constructors
What is the primary purpose of a constructor in Java?