Unit 3 Cycle 2 Day 16: Constructor with Validation
Share
Constructor with Validation
Section 3.2 — Constructors
Key Concept
Constructors can include validation logic to ensure objects are created in a valid state. A constructor might check that a parameter is within an acceptable range and assign a default value if it is not: if (age < 0) this.age = 0; else this.age = age;. The AP exam tests whether constructor validation correctly handles edge cases and what the object's state is after construction with invalid arguments. Validation in constructors is a key encapsulation practice.
Consider the following class.
What does new Score(150).getValue() return?
Answer: (B) 100
150 > 100, so the else-if branch sets value = 100. The constructor clamps the input to the range [0, 100].
Why Not the Others?
(A) The constructor does not blindly accept the argument. It clamps to 0-100.
(C) 0 is used when v < 0, not when v > 100.
(D) Constructors can contain logic like if-else statements.
Common Mistake
Constructors can validate input and enforce constraints. This is a key benefit of encapsulation: the class controls what values are stored.
AP Exam Tip
Defensive constructors that validate input are common in AP exam FRQs. Look for boundary conditions and clamping logic.