Constructors

A constructor is the method that prepares a new object. It has the name of the class, no return type, and it runs once for every new. A class may have several, as long as their parameter lists differ, and one constructor may call another with this(...).

A constructor

The point below has two fields, and the constructor stores its two arguments in them. The class keeps them final, so the constructor is the only place that can assign them, and the object cannot change afterwards.

The file Point.java:

public class Point { private final int x; private final int y; Point() { this(0, 0); } Point(int x, int y) { this.x = x; this.y = y; } Point(Point other) { this(other.x, other.y); } @Override public String toString() { return "(" + x + ", " + y + ")"; } public static void main(String[] args) { Point origin = new Point(); Point p = new Point(3, 4); Point copy = new Point(p); System.out.println("origin: " + origin); System.out.println("p: " + p); System.out.println("copy: " + copy); System.out.println("same: " + (p == copy)); } }

javac -Xlint:all Point.java
java Point

origin: (0, 0)
p: (3, 4)
copy: (3, 4)
same: false

The no-argument constructor calls the two-argument one with zeros, so there is one place that assigns the fields. The copy constructor reads the fields of another Point and passes them on; the copy has the same values and a different identity, which is the last line.

Overloaded constructors

Overloading works for constructors exactly as it does for methods: the compiler chooses by the number and types of the arguments. The three constructors above are Point(), Point(int, int) and Point(Point), and each call in main matches one of them.

Two constructors that differ only in the names of their parameters are the same constructor, and the compiler refuses the second. A constructor may also be private, which is how a class forbids direct creation and offers a static factory method instead.

this(...)

this(...) calls another constructor of the same class. It must be the first statement of the constructor, because Java initialises an object once and in one order: the fields, the called constructor, then the rest of the body. The no-argument and copy constructors above use it to keep the assignment in one place.

A copy constructor

Point(Point other) is a copy constructor: it takes an object of its own class and builds a second one with the same values. For a class with only primitive fields a field-by-field copy is enough; a class with an array or a collection must decide whether the copy shares it or copies it, which is the defensive copy of lesson 042.

The default constructor

A class with no constructor at all gets a default one with no parameters and an empty body. It exists only while the class has no written constructor: the moment one is declared, the default one is gone and new Plain() needs a written no-argument constructor.

public class Default { public static void main(String[] args) { Plain plain = new Plain(); System.out.println(plain.value); } } class Plain { int value = 7; }

javac -Xlint:all Default.java
java Default

7

The field initialiser runs before the constructor body, so the value is 7 in every object the default constructor makes. A field with no initialiser would be 0 or null, as lesson 008 showed.

When the arguments do not match

A call with a parameter list that matches no constructor is a compile error, and the message lists what the compiler found and what it needed:

public class ConstructorError { public static void main(String[] args) { Point p = new Point(1); System.out.println(p); } } class Point { private final int x; private final int y; Point(int x, int y) { this.x = x; this.y = y; } }

javac -Xlint:all ConstructorError.java

ConstructorError.java:3: error: constructor Point in class Point cannot be applied to given types;
Point p = new Point(1);
^
required: int,int
found: int
reason: actual and formal argument lists differ in length
1 error

The three detail lines say what a reader needs: the signature that exists, the arguments that were given, and the reason in words. The class in this example has one constructor, so the default one that would accept new Point() does not exist either.

Exercises

  1. Add a constructor Point(int both) that sets x and y to the same value.
  2. Make the copy constructor of Point.java share a mutable field, add such a field, and observe the difference.
  3. Add a constructor to Default.java that takes a value and check whether new Plain() still compiles.
  4. Call new Point(1, 2, 3) and read the whole error.

Questions

A new set of questions in a new order every time. Choose one answer for each, then check.

  1. What is the name of a constructor?

    Answer

    The name of the class

    A constructor is identified by the class name and has no return type.

  2. Where must this(...) stand in a constructor?

    Answer

    As the first statement of the constructor body

    The call to another constructor must come before any other work in the constructor body.

  3. When does a class get a default constructor?

    Answer

    When it declares no constructor at all

    The compiler adds one only if no constructor is written; a written constructor removes it.

  4. What does this program print? public class Q1 { public static void main(String[] args) { P p = new P(); System.out.println(p.x + " " + p.y); } } class P { int x; int y; P() { this(1, 2); } P(int x, int y) { this.x = x; this.y = y; } }

    Answer

    1 2

    The no-argument constructor delegates to the two-argument one with 1 and 2.

  5. What does this program print? public class Q2 { public static void main(String[] args) { P a = new P(3, 4); P b = new P(a); b.x = 9; System.out.println(a.x + " " + b.x); } } class P { int x; int y; P(int x, int y) { this.x = x; this.y = y; } P(P other) { this(other.x, other.y); } }

    Answer

    3 9

    The copy has its own fields, so changing b.x leaves a.x at 3.

  6. What does this program print? public class Q3 { public static void main(String[] args) { P p = new P(); System.out.println(p.x); } } class P { int x = 5; }

    Answer

    5

    The default constructor runs the field initialiser, and x starts at 5.

  7. What is the first line of the compiler output for this program? public class Q4 { public static void main(String[] args) { P p = new P(1); } } class P { P(int x, int y) { } }

    Answer

    error: constructor P in class P cannot be applied to given types;

    The only constructor takes two ints, so a call with one argument does not match.

  8. What does a copy constructor take?

    Answer

    An object of the same class

    It reads the values of another instance and builds a second object from them.

  9. What does this program print? public class Q5 { public static void main(String[] args) { P a = new P(2); P b = new P(a); System.out.println(a == b); } } class P { int x; P(int x) { this.x = x; } P(P other) { this(other.x); } }

    Answer

    false

    The copy constructor creates a new object, so the two references differ.

  10. What does this program print? public class Q6 { public static void main(String[] args) { P p = new P(); System.out.println(p.x + " " + p.y); } } class P { final int x; final int y; P() { this(0, 0); } P(int x, int y) { this.x = x; this.y = y; } }

    Answer

    0 0

    The no-argument constructor calls the other one with zeros, and final fields may be assigned there.

The code on this page was built with OpenJDK 21.0.13 (javac and java) and run on Alpine Linux in a Docker container.

Article author: Arthur Isaev