Unit 3 Cycle 1 Day 3: Constructor Parameter vs Instance Variable
Share
Constructor Parameter vs Instance Variable
Section 3.2 — Constructors
Key Concept
When a constructor parameter has the same name as an instance variable, the parameter shadows the field. Inside the constructor, the unqualified name refers to the parameter, not the instance variable. Use this.variableName to explicitly refer to the instance variable. A common AP exam error is name = name which assigns the parameter to itself, leaving the instance variable unchanged. The correct form is this.name = name, which assigns the parameter value to the instance variable.
Consider the following constructor.
What does new Student("Alice", 10).getName() return?
Answer: (B) null
The constructor assigns the parameter to itself (name = name refers to the parameter both times, not the instance variable). The instance variable name remains at its default value of null. The fix: use this.name = name.
Why Not the Others?
(A) The instance variable is never assigned. The parameter shadows the instance variable.
(C) String instance variables default to null, not empty string.
(D) The code compiles without errors. The bug is a logic error, not a syntax error.
Common Mistake
When a parameter has the same name as an instance variable, the parameter shadows the field. name = name assigns the parameter to itself. Use this.name = name to access the instance variable.
AP Exam Tip
The this keyword distinguishes instance variables from parameters with the same name. Without this, Java uses the closest scope (the parameter). This is a very common AP exam trap.