Skip to content
Tutorials Center
My learning

Topics

Lesson 49 of 201 ยท Object-Oriented Programming

Constructors

Learn Java constructors - default and parameterized constructors, overloading, this(...) chaining, validating arguments, initialization order, Java 25 flexible bodies and copy constructors.

In the last two lessons you created objects with new and then filled in their fields one by one. That has two problems. It's tedious, and worse, there's a moment when the object exists but isn't ready: a Point with no coordinates, an Account with no owner. If someone forgets a line, the half-built object travels through the program until it causes a NullPointerException far away.

A constructor fixes both. It's a special block of code that runs as part of new, receives the starting values, checks them, and sets up the fields, so every object is complete and valid from the moment it exists. This lesson covers the default constructor, parameterized and overloaded constructors, chaining with this(...), validation, the order in which initialization happens, the new flexible constructor bodies in Java 25, and copy constructors.

Declaring a constructor

A constructor looks like a method, with two differences: its name is exactly the class name, and it has no return type, not even void.

Java A constructor that sets up the object

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

new Point(1, 2) allocates the object, sets the fields to defaults, and then calls the constructor with 1 and 2. Inside, the parameters x and y have the same names as the fields, so they shadow them. this.x means "the field x of the object being built", and x alone means the parameter. This naming pattern is used in almost every Java class; The this Keyword looks at this in detail.

The fields are final, which works perfectly with constructors: a final field must be assigned exactly once, and the constructor is the place to do it. The compiler even checks that every constructor assigns every final field.

Adding a return type turns a constructor into an ordinary method. void Point(double x, double y) { ... } compiles, but it's a method that happens to be called Point, and new Point(1, 2) then fails because no matching constructor exists. If your constructor seems to be ignored, check for a stray void.

The default constructor

If a class declares no constructors at all, the compiler adds one for you: a no-argument constructor with an empty body. That's why new Book() worked in earlier lessons. It's called the default constructor.

The moment you write any constructor yourself, the default one is no longer generated. Code that relied on it breaks. This example fails to compile on purpose:

Java The vanished default constructor

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

javac says constructor Book in class Book cannot be applied to given types; followed by required: String and found: no arguments. If you also want a no-argument version, write it yourself, as the next section shows. Often, though, the error is a good thing: it stops people from creating books without titles.

Overloading constructors

A class can have several constructors, as long as their parameter lists differ, exactly like method overloading. Each one offers a different way to build the object:

Java
class Pizza {
    String size;
    List<String> toppings;

    Pizza() { ... }                                     // a plain medium pizza
    Pizza(String size) { ... }                          // choose the size
    Pizza(String size, List<String> toppings) { ... }   // choose everything
}

Writing the same field assignments in all three constructors would be repetitive and error-prone. Java has a better way.

Chaining constructors with this(...)

Inside a constructor, this(arguments) calls another constructor of the same class. The usual pattern: one "full" constructor does the real work, and the shorter ones fill in defaults and delegate to it.

Java Constructor chaining with this(...)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

The trace shows the chain: new Pizza() calls Pizza("medium"), which calls the full constructor. The full constructor's body finishes first, then control returns to each caller in turn. All defaults live in one obvious place, and every field is assigned in exactly one constructor.

The rules for this(...):

  • It can only appear in a constructor, and at most once.
  • Until Java 25, it had to be the very first statement. Java 25 relaxes this; see flexible constructor bodies below.
  • Constructors can't call each other in a cycle; the compiler reports recursive constructor invocation.

List.copyOf(toppings) stores an unmodifiable copy, so a caller who later changes their own list can't change the pizza. That's a defensive copy, a technique covered in Encapsulation.

Validating arguments

A constructor is the gatekeeper of an object: if it rejects bad input, an invalid object can never exist. The usual way to reject input is to throw an exception, which stops new from completing, so no object is ever handed out.

Java A constructor that refuses bad data

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

The checks follow a common pattern:

  • Objects.requireNonNull(x, message) throws NullPointerException with your message when x is null, and returns x otherwise. It's the standard one-line null check.
  • IllegalArgumentException signals "this argument is not acceptable". Include the bad value in the message; it saves debugging time.
  • Validate before assigning fields, so the rules are visible at the top.

Exceptions get a full chapter starting with Exceptions and try-catch. For now, the key idea is: validate in the constructor, and every method can trust the fields.

What happens during new, in order

When you write new Pizza("large"), Java performs these steps:

  1. Memory is allocated and every field is set to its default (0, false, null).
  2. The chosen constructor starts. If it begins with this(...), that constructor runs first (recursively, following these same steps from here).
  3. Otherwise, the superclass constructor runs (super(...), implicit if you don't write it; every class has a superclass, at least Object; see Inheritance).
  4. Field initializers and instance initializer blocks run, in the order they appear in the class.
  5. The rest of the constructor body runs.
Java Watching the initialization order

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

The field initializer runs before the constructor body, which is why the body already sees status=NEW and items=3. Calling new Order() instead would print the same lines plus a last line from the no-argument constructor; the initializers still run only once, in the constructor that doesn't start with this(...).

A practical consequence: don't call methods that subclasses can override from a constructor. The subclass's fields aren't initialized yet when the parent's constructor runs, so the overridden method sees defaults. Inheritance shows this trap.

Java 25: flexible constructor bodies

Before Java 25, this(...) or super(...) had to be the first statement, so you couldn't validate or compute arguments before delegating, which forced awkward helper methods. Java 25 finalized flexible constructor bodies (JEP 513): you may now put statements before this(...) or super(...), as long as they don't use the object being built (no reading its fields, no calling its instance methods). One exception: you may assign the class's own fields there, if they have no initializer.

Java Validating before this(...) in Java 25

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Code written for Java 24 or earlier can't do this, and you'll see plenty of such code, so recognize both styles. The older workaround was a static helper method called inside the argument list: this(parseLow(text), parseHigh(text)).

Copy constructors

A copy constructor takes another object of the same class and builds a new object with the same state. It's the clearest, safest way to copy objects in Java, much simpler than clone() (see Copying Objects).

The important question is how deep the copy goes. Copying a reference to a mutable list gives a shallow copy: both objects share the list. Creating a new list gives a deep (independent) copy:

Java Shallow vs deep copy constructors

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

The shallow copy sees "Song C" appear, because it shares the original's list. The deep copy doesn't. Rules of thumb for copy constructors:

  • Immutable fields (String, Integer, LocalDate, records of immutable values) can be shared safely.
  • Mutable fields (lists, arrays, maps, your own mutable objects) need their own copy.
  • The JDK uses the same idea: new ArrayList<>(otherList) and new HashMap<>(otherMap) are copy constructors.

The example also shows a private constructor, usable only inside the class. Combined with a public static method that calls it, that's a static factory, a popular alternative to public constructors because the method can have a descriptive name (Playlist.shallowCopyOf, List.of, LocalDate.of).

Constructor checklist

  • Give each class the constructors that make sense for it, and no more. If an object can't be valid without a value, require it as a parameter.
  • Put the real work in one constructor and chain the others to it with this(...).
  • Validate arguments and fail fast with clear messages; use final fields where values never change.
  • Copy mutable arguments you store, and copy mutable fields in copy constructors.
  • Keep constructors simple: no long computations, no I/O, no calls to overridable methods.
  • For classes that only carry data, consider a record, which generates the constructor (plus accessors, equals, hashCode and toString) for you.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. A class declares only Car(String model) { ... }. What does new Car() do?

    The compiler adds a no-argument constructor only when a class declares no constructors at all. Once you write one, you must write a no-arg version yourself if you want it.
  2. 2. In Pizza() { this("medium"); }, what does this("medium") do?

    this(...) inside a constructor delegates to another constructor of the same class; it builds the same object, not a new one.
  3. 3. What is printed? class A { int n = 5; A() { System.out.println(n); n = 9; } } then new A();

    Field initializers run before the constructor body, so n is already 5 when the body prints it. It becomes 9 afterward.
  4. 4. Why does void Point(int x, int y) { ... } not work as a constructor?

    Constructors have no return type. Adding void declares a method with the class's name, so new Point(1, 2) finds no matching constructor.
  5. 5. A copy constructor does this.items = other.items; where items is an ArrayList. What happens when the original adds an item afterward?

    Copying the reference makes a shallow copy; both objects point to the same list. Use new ArrayList<>(other.items) for an independent copy.

Summary

  • A constructor has the class's name and no return type; it runs as part of new and sets up the object.
  • The compiler generates a no-argument default constructor only if the class declares no constructors.
  • Constructors can be overloaded; chain them with this(...) so one constructor does the real work.
  • Validate arguments in the constructor (Objects.requireNonNull, IllegalArgumentException) so invalid objects never exist; final fields must be assigned in every constructor.
  • Order inside new: defaults, then super(...), then field initializers, then the constructor body.
  • Java 25 allows statements before this(...)/super(...) as long as they don't use the object being built.
  • Copy constructors create a new object from an existing one; copy mutable fields for a deep, independent copy.

Next: The this Keyword, where you'll use this to refer to the current object, pass it to other methods and build fluent APIs.