Unit 3 Cycle 1 Day 2: Constructor Overloading
Share
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.
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.