Unit 3 Cycle 1 Day 26: Constructor and Method Tracing

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

Constructor and Method Tracing

Section Mixed — Review: Class Design

Key Concept

Constructor and method tracing in class hierarchies requires tracking which constructor runs, what values are assigned, and which version of each method is called. When a subclass object is created, the constructor chain initializes the object from superclass down. When methods are called, overridden versions execute based on the runtime type. The AP exam combines these concepts: creating an object triggers constructor tracing, then method calls trigger polymorphic dispatch. Track both the construction order and the method resolution independently.

Consider the following class.

public class Counter { private int val; public Counter(int start) { val = start; } public Counter add(int n) { val += n; return this; } public int getVal() { return val; } }

What does new Counter(0).add(5).add(3).getVal() return?

Answer: (C) 8

Counter starts at 0. add(5): val=5, returns this. add(3): val=8, returns this. getVal(): returns 8. Method chaining works because add() returns this.

Why Not the Others?

(A) 5 is the value after the first add, but the second add(3) makes it 8.

(B) 3 is the argument to the second add, not the total.

(D) 0 is the initial value before any additions.

Common Mistake

Method chaining: when a method returns this, you can call another method on the result immediately. Each call modifies the same object.

AP Exam Tip

Method chaining (returning this) allows fluent API calls like obj.method1().method2(). Trace each method call in order.

Review this topic: Section Mixed — Review: Class Design • Unit 3 Study Guide

More Practice

Back to blog

Leave a comment

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