Unit 3 Cycle 1 Day 10: The this Keyword

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

The this Keyword

Section 3.10 — The this Keyword

Key Concept

The this keyword refers to the current object within a method or constructor. It is used to disambiguate between instance variables and parameters with the same name (this.name = name), to pass the current object as an argument (otherObj.method(this)), and to call another constructor from a constructor (this(args)). The this reference is implicitly available in all non-static methods. On the AP exam, understanding this is crucial for constructor chaining and for methods that compare the current object to another.

Consider the following class.

public class Player { private String name; private int score; public Player(String name, int score) { this.name = name; this.score = score; } public boolean beats(Player other) { return this.score > other.score; } }

What does the following code print?
Player p1 = new Player("A", 50); Player p2 = new Player("B", 30); System.out.println(p1.beats(p2));

Answer: (A) true

p1.beats(p2): this refers to p1 (score=50). other is p2 (score=30). 50 > 30 is true.

Why Not the Others?

(B) 50 IS greater than 30, so the method returns true.

(C) The method returns a boolean, not an int.

(D) The code compiles. A method can receive another object of the same class as a parameter.

Common Mistake

this refers to the object the method is called ON. In p1.beats(p2), this is p1 and other is p2. A method can access private fields of another object of the same class.

AP Exam Tip

A class can access private fields of any object of the same class, not just this. The beats method accesses other.score even though score is private.

Review this topic: Section 3.10 — The this Keyword • Unit 3 Study Guide

More Practice

Back to blog

Leave a comment

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