Topic 3.9 — this Keyword

Goal: use this to refer to the current object, especially to resolve shadowing and to access instance variables/methods from inside the class.

The big idea

Inside an instance method or constructor, this is a reference to the current object (the object the method is running on).

You use this most often to fix shadowing and make it clear which variable is the field.

Where you can use this

  • Inside instance methods (not static methods)
  • Inside constructors
  • To refer to instance variables and instance methods

Shadowing problem (common AP trap)

If a parameter has the same name as an instance variable, the parameter “hides” the instance variable.

public class Student {
  private int grade;

  public void setGrade(int grade) {
    grade = grade;  // ❌ sets the parameter to itself
  }
}

The left grade is the parameter, not the field.

Fix using this

Use this.grade to mean “the field named grade.”

public void setGrade(int grade) {
  this.grade = grade;  // ✅ field = parameter
}

this in constructors

Same idea: it helps you initialize fields clearly.

public class Student {
  private String name;

  public Student(String name) {
    this.name = name;
  }
}

Calling instance methods with this

You can call methods like this.doThing(), but most of the time it’s optional.

public void reset() {
  this.setGrade(0); // works
  // setGrade(0);   // also works (same object)
}

this is NOT used in static methods

Static methods don’t run on a specific object, so there is no “current object.”

public static void demo() {
  // System.out.println(this); // ❌ not allowed
}

Quick self-check

  1. What does this refer to?
  2. Why does grade = grade; usually do nothing useful?
  3. Rewrite name = name; correctly inside a constructor.
  4. Can you use this in a static method? Why/why not?
  5. Is this.method() different from method() inside an instance method?

← Back to Unit 3 topics