AP® Computer Science A · Unit 3 · Topic 3.4

Overloaded Constructors

Overloaded constructors let a class be built in several ways, each with a different parameter list. Java decides which one runs by matching the number and types of arguments in the call.

A class often needs more than one way to get started. Sometimes you know every value up front, sometimes you want sensible defaults, sometimes you're copying another object. Overloading lets you write several constructors with the same name but different parameter lists, one for each situation, instead of forcing every caller to supply values they don't have.

Java picks which constructor runs by matching the call's argument list against each constructor's parameter list, checking the number of arguments and their types. There's no guessing or best-fit search beyond that: the call new Point() matches a constructor with zero parameters, and new Point(3, 4) matches one with two int parameters. If no constructor's signature matches, the code fails to compile.

This matters most right after you learn that a class gets a free no-argument constructor only when it defines no constructors at all. Write any constructor yourself, even a one-argument one, and that free default vanishes, so a once-working no-argument call breaks until you write Rectangle() by hand. Constructors can also call each other with this(...), so a no-argument constructor can hand off to a full one and fill in defaults instead of repeating the same assignment lines twice.

Key terms

Overloading
Defining multiple methods or constructors with the same name but different parameter lists.
Constructor
A block of code that runs once when an object is created, usually to set its initial field values.
Signature
The number, order, and types of a constructor's or method's parameters, used to tell overloaded versions apart.
Default constructor
The no-argument constructor Java automatically supplies only if a class defines no constructors itself.
this(...)
A call inside one constructor that runs another constructor in the same class.

Watch it explained

  1. How it worksHow does Java pick which constructor to run by matching the list of arguments?
  2. Worked exampleFind which of two Point constructors runs for new Point() and for new Point(3, 4).
  3. Common mistakeWhy does adding your own constructor make new Rectangle() suddenly stop compiling?
  4. Going furtherWhat changes when one constructor calls another with this instead of repeating the code?

Check yourself

Your turn1 of 2
A Point class has Point() setting x and y to 0, and Point(int x, int y) setting them from arguments. Which constructor runs for new Point(3, 4)?

End of topic.