Unit 3 · 14 min
3.9 this Keyword
this is how an object refers to itself.
Summary, objectives and course and exam description (CED) codes
Inside an instance method or a constructor, the keyword this is a special variable that holds a reference to the current object, the object whose method or constructor is being called. You can use this to reach an instance variable hidden by a parameter (this.name = name) or to pass the current object as an argument. Class methods do not have a this reference.
By the end of this session you can
- 3.9.A Develop code for expressions that are self-referencing, and determine the result of these expressions.
Reviewed against the CED on
1LearnThe notes, the traps and how to remember them
1. this: a reference to the current object
Inside an instance method or a constructor, the keyword this acts as a special variable that holds a reference to the current object: the object whose method or constructor is being called 3.9.A.1.
The most common use is in a constructor whose parameters have the same names as the instance variables. The parameter hides the instance variable (topic 3.8), and this. names the instance variable.
public class Runner
{
private String name;
private double kilometers;
public Runner(String name, double kilometers)
{
this.name = name; // instance variable = parameter
this.kilometers = kilometers;
}
public void run(double kilometers)
{
this.kilometers += kilometers; // add the parameter to the total
}
public String getName()
{
return name;
}
public double getKilometers()
{
return kilometers;
}
public String toString()
{
return name + " " + kilometers + " km";
}
}
Runner r = new Runner("Ivy", 5.0);
r.run(3.5);
System.out.println(r);
Output:
Ivy 8.5 km
(println(r) uses the class’s toString method; writing toString is background, outside the AP® exam.) In the call r.run(3.5), the current object is the one r refers to, so inside run, this and r are references to the same object.
r [ ref ] ---+
+---> Runner object: name "Ivy", kilometers 8.5
this [ ref ] ---+ (inside run, during the call r.run(3.5))
2. Which object is this?
The same method can run for many objects. Each time, this refers to the object the method was called on 3.9.A.1. Comparing this with a parameter using == checks whether they are the same object.
public class Badge
{
private String owner;
public Badge(String owner)
{
this.owner = owner;
}
public String whoAmI()
{
return "I belong to " + this.owner;
}
public boolean isSameBadge(Badge other)
{
return this == other;
}
}
Badge a = new Badge("Omar");
Badge b = new Badge("Jun");
Badge c = a;
System.out.println(a.whoAmI());
System.out.println(b.whoAmI());
System.out.println(a.isSameBadge(c) + " " + a.isSameBadge(b));
Output:
I belong to Omar
I belong to Jun
true false
In a.isSameBadge(c), this refers to the object a refers to, and other is a copy of the reference in c. Both point to the same object, so == is true.
Watch out: in whoAmI, writing owner or this.owner gives the same result, because no parameter or local variable is named owner. this. is required only when a local name hides the instance variable.
3. Passing this as an argument
The keyword this can be used to pass the current object as an argument in a method call 3.9.A.2. That lets another object store or use a reference to the current object.
public class Room
{
private int number;
private Guest occupant;
public Room(int number)
{
this.number = number;
occupant = null;
}
public void assign(Guest g)
{
occupant = g;
}
public String describe()
{
if (occupant == null)
{
return "Room " + number + ": empty";
}
return "Room " + number + ": " + occupant.getName();
}
}
public class Guest
{
private String name;
public Guest(String name)
{
this.name = name;
}
public String getName()
{
return name;
}
public void checkInto(Room r)
{
r.assign(this); // pass the current Guest object to the room
}
}
Room r12 = new Room(12);
Room r14 = new Room(14);
Guest maya = new Guest("Maya");
maya.checkInto(r12);
System.out.println(r12.describe());
System.out.println(r14.describe());
Output:
Room 12: Maya
Room 14: empty
During maya.checkInto(r12), this refers to the Guest object that maya refers to. r.assign(this) passes that reference, so the room’s occupant and maya become aliases of one Guest object.
4. Class methods have no this
Class methods (static methods) are called on the class, not on an object, so they do not have a this reference 3.9.A.3.
public class Counter
{
private int count;
public static void resetAll()
{
this.count = 0;
}
}
Compiler says:
error: non-static variable this cannot be referenced from a static context
| Where the code is | Is there a this? |
|---|---|
| Constructor | Yes: the object being constructed 3.9.A.1 |
| Instance method | Yes: the object the method was called on 3.9.A.1 |
| Class (static) method | No 3.9.A.3 |
Lock it in: memory hooks
- thisthis = me, the object running this code right now.
- Constructorsthis.name = name: "my name gets the name you gave me".
- staticNo object, no this: static methods never have one.
Common misconceptions
"this refers to the class."
Not quite. this refers to one object: the object whose method or constructor is running right now. Two different objects calling the same method have two different this references.
"this can be used anywhere in a class."
Not quite. Class (static) methods are not called on an object, so they have no this reference. Using this in a static method does not compile.
"this.name and name always mean the same thing."
Not quite. They are the same only when no local variable or parameter is called name. When a parameter is called name, name means the parameter and this.name means the instance variable.
Exam traps
- In obj.method(), this inside method refers to the same object as obj: they are aliases.
- this.title = title; works; title = this.title; copies the instance variable into the parameter instead.
- this in a static method is a compile error: non-static variable this cannot be referenced from a static context.
2PracticeRecall it, then check yourself
In 30 seconds
- In an instance method or constructor, this holds a reference to the current object.
- The current object is the object whose method or constructor is being called.
- this.variable names the instance variable, even when a parameter has the same name.
- this can be passed as an argument to give another method a reference to the current object.
- Class methods do not have a this reference.
Cover this list, say the points out loud, then take the checkpoint without scrolling back up.
Checkpoint · 5 questions
Checkpoint: this Keyword
Pick an answer to mark it. Every answer is explained, and you can try any question again. Your saved score counts first tries only, and stays in this browser.
3PrevailLock it in for exam day
By the numbers
- Where this can be used two places CED 3.9.A.1, 3.9.A.3
- Common uses of this two uses CED 3.9.A.1, 3.9.A.2
- this.variable to name an instance variable hidden by a parameter or local variable
- passing this as an argument in a method call
Key terms: flip the cards
Read the term, say the definition out loud, then flip to check. Struggling a little to remember is what makes it stick.
-
thistap to flip
A special variable inside an instance method or constructor that holds a reference to the current object, the object whose method or constructor is running.
Example and CED codes -
Instance variabletap to flip
An attribute declared in a class outside any method or constructor, whose value is unique to each object of the class.
Example and CED codes -
Object referencetap to flip
The value a reference variable holds: it can be thought of as the memory address of the object.
Example and CED codes -
Parametertap to flip
A variable declared in the header of a method or constructor. It receives the value passed in and can be used in the body.
Example and CED codes -
Argumenttap to flip
A value passed into a method or constructor when it is called.
Example and CED codes -
Scopetap to flip
The part of a program where a variable can be used, set by the block in which the variable is declared.
Example and CED codes -
Class variabletap to flip
An attribute declared with the keyword static that belongs to the class, so all objects of the class share a single copy.
Example and CED codes
Questions students ask
What does the this keyword mean in Java?
Inside an instance method or constructor, this is a reference to the current object, the object whose method or constructor is being called.
Why do constructors use this.name = name?
The parameter has the same name as the instance variable, so name alone means the parameter. this.name means the current object's instance variable, so the statement stores the parameter's value in the object.
Can you use this in a static method?
No. A static (class) method is called on the class, not on an object, so there is no current object and no this reference. The code does not compile.
What does passing this as an argument do?
It gives the called method a reference to the current object, so that method or the object it belongs to can use or store the current object.