AP® Computer Science A · Unit 3 · Topic 3.9

The this Keyword

this is a reference to the exact object whose method is currently running. It lets code refer to the object's own fields even when a parameter has the same name.

Every object method runs on behalf of some specific object, and this is how the code inside that method talks about that object. When you write a method in a class, you don't know in advance which object will call it — maybe a Student named Ava, maybe one named Ben. this always means 'whichever object is actually running this method right now.' That's the intuition: a class is a blueprint shared by many objects, so the blueprint needs a word that means 'me, the one currently executing' rather than naming any one object directly.

The most common use is in constructors, where a parameter and a field legitimately deserve the same name. Inside the method, a bare name refers to the closest variable in scope, which is the parameter. Writing this.name forces Java to look at the object's own field instead, so this.name = name copies the parameter's value into the field without any renaming tricks. You can also pass this as an argument to another method, handing over a reference to the entire current object so that method can read or modify it directly — useful when one object needs to register itself with another.

Static methods don't get a this, because this only makes sense attached to an object, and static methods belong to the class itself, callable before any object exists. That distinction connects back to the private fields and constructors earlier in this unit: this is the mechanism that makes encapsulation work smoothly, letting constructors and instance methods always find the right object's data even when local names collide.

Key terms

this
A reference inside an instance method or constructor to the specific object currently running that code.
instance field
A variable declared in a class that each object gets its own separate copy of.
parameter shadowing
When a parameter or local variable has the same name as a field, temporarily hiding the field's name in that scope.
static method
A method that belongs to the class itself rather than to any object, and can run without an object existing.

Watch it explained

  1. How it worksHow does this point back at the exact object whose method is currently running?
  2. Worked exampleTrace a constructor that writes this.name = name when both names are spelled the same.
  3. How it worksHow does passing this as an argument hand the whole current object to another method?
  4. Common mistakeWhy doesn't a static method have a this reference available to use?

Check yourself

Your turn1 of 2
A constructor is written as Student(String name) { this.name = name; }, where the parameter and the instance field share the same name. What does this.name = name; actually do?

End of topic.