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
  }
}
Note: The keyword this refers to the object being built. Writing this.model = model tells Java: assign the parameter named model to the field named model. Without this, both names would refer to the parameter and the field would never get set.

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.

TermMeaning
Default constructorThe empty, no-argument constructor Java adds automatically when you write none.
Parameterized constructorA constructor that accepts arguments to set initial field values.
Overloaded constructorsTwo or more constructors in one class, each with a different parameter list.
this keywordA reference to the current object, used to reach its own fields and methods.
Note: The moment you write even one constructor of your own, Java stops providing the free default constructor. If you still want a no-argument option, add it yourself.

Exercise: Java Constructors

What is the primary purpose of a constructor in Java?