Unit 3 Cycle 2 Day 16: Constructor with Validation

Unit 3 Advanced (Cycle 2) Day 16 of 28 Advanced

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.

public class Score { private int value; public Score(int v) { if (v < 0) value = 0; else if (v > 100) value = 100; else value = v; } public int getValue() { return value; } }

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.

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.