Unit 3 Cycle 1 Day 2: Constructor Overloading

Unit 3 Foundation (Cycle 1) Day 2 of 28 Foundation

Constructor Overloading

Section 3.2 — Constructors

Key Concept

Constructor overloading allows a class to have multiple constructors with different parameter lists. Java determines which constructor to call based on the number and types of arguments provided at object creation. A no-argument constructor sets default values, while a parameterized constructor allows custom initialization. If you define any constructor, Java no longer provides the default no-argument constructor. Overloaded constructors often call each other using this(args) to avoid duplicating initialization code.

Consider the following class.

public class Point { private int x; private int y; public Point() { x = 0; y = 0; } public Point(int x, int y) { this.x = x; this.y = y; } public String toString() { return "(" + x + ", " + y + ")"; } }

What does System.out.println(new Point(3, 7)); print?

Answer: (A) (3, 7)

The two-argument constructor sets x=3, y=7. println calls toString() automatically, which returns "(3, 7)".

Why Not the Others?

(B) (0, 0) would result from the no-arg constructor new Point().

(C) The class overrides toString(), so the default Object reference is not printed.

(D) The code compiles. The two-arg constructor matches the call new Point(3, 7).

Common Mistake

When a class has multiple constructors (overloading), Java selects the one whose parameters match the arguments. println automatically calls toString() on objects.

AP Exam Tip

System.out.println(obj) always calls obj.toString(). If toString() is overridden, it uses the custom version. This is tested frequently.

Review this topic: Section 3.2 — Constructors • Unit 3 Study Guide

More Practice

Back to blog

Leave a comment

Please note, comments need to be approved before they are published.