AP Computer Science A · Unit 3: Class Creation
3.9 this Keyword
What is the this keyword?
this is a reference to the current object — the instance whose method or constructor is running. It's used inside a class to refer to instance variables or invoke other constructors, especially when a parameter name shadows an instance variable name.
Resolving name conflicts
When a constructor or method parameter has the same name as an instance variable, Java assumes the local parameter unless you use this.variableName. Writing `this.age = age;` tells Java to assign the parameter value to the object's instance variable, not itself.
Calling other constructors
this(...) can be used as the first statement in a constructor to call another constructor in the same class, avoiding duplicate code. This is called constructor chaining — one constructor sets defaults, and another calls it with `this(...)` to reuse that logic.
Key terms
- this keyword
- A reference to the current object executing a method or constructor.
- Why use this.variableName?
- To distinguish an instance variable from a parameter or local variable with the same name.
- this(...) constructor call
- Calls another constructor in the same class; must be the first statement in a constructor.
- Constructor chaining
- Using this(...) to have one constructor invoke another, reducing duplicate initialization code.
- What happens without 'this' when names conflict?
- The parameter shadows the instance variable, so the instance variable is never updated.
Try an AP-style question
Code
private int size;
public void setSize(int size) {
this.size = size;
}What does this.size refer to?
- The parameter
- The instance variable
- A static variable
- A new object
Show the answer
B. Disambiguates.
Practice 8 AP-style questions with instant explanations, flashcards and spaced review.
Study 3.9 free in APrep