AP® Computer Science A review sheet from Aim for Five (aimforfive.com/csa/units/3/3-9)
Unit 3 · Topic 3.9
3.9 this Keyword
Inside an instance method or constructor, the keyword this refers to the object the code is running for. This topic covers using this to reach instance variables that a parameter shadows, and passing this to another method.
Key terms
this- current object
- instance variable vs. parameter
What this means
Every instance method call and every constructor call is running for one particular object. In a.isLongerThan(b), that object is a. Inside the method, the keyword this is a reference to that object, the current object.
So this.seconds means "the seconds of the object this method was called on". Most of the time you don't need to write this., because an instance variable's name already means the current object's copy. But it's always allowed, and sometimes it's needed.
The same goes for calling another instance method from inside the class. Writing this.isLongerThan(other) and writing isLongerThan(other) both call the method on the current object.
When a method compares the current object with a parameter of the same class, this and the parameter are usually two different objects. Keep them straight by naming them in your trace: "this is song a, other is song b".
Setting shadowed instance variables
In 3.8, a parameter with the same name as an instance variable hid the instance variable. this gets around that:
public class Song
{
private String title;
private int seconds;
public Song(String title, int seconds)
{
this.title = title;
this.seconds = seconds;
}
public boolean isLongerThan(Song other)
{
return this.seconds > other.seconds;
}
public String longerTitle(Song other)
{
if (other.isLongerThan(this))
{
return other.title;
}
return title;
}
}
In the constructor, this.title is the instance variable and plain title is the parameter, so this.title = title; copies the parameter into the object. This style is very common, so read it carefully. Leaving off this. on the left side brings back the shadowing bug from 3.8, and the instance variable stays at its default value. Giving the parameter a different name, like t, works just as well; both styles earn full credit.
Passing this as an argument
Because this is a reference to the current object, you can pass it to a method. In longerTitle, the call other.isLongerThan(this) asks the other song whether it's longer than the current one. Inside that call, the roles swap: this means other, and the parameter refers to the original song.
No this in static methods
A static method isn't called on any object, so it has no this. Using this inside a static method is a compile error, just like using an instance variable there (3.7). Constructors, on the other hand, do have this: it's the new object being built.
Worked examples
Try each one yourself first, then open the solution.
- Example 1
Tracing with this
Using the
Songclass above, what does this code print?Song a = new Song("Ripple", 215); Song b = new Song("Glow", 248); System.out.println(a.isLongerThan(b)); System.out.println(a.longerTitle(b)); System.out.println(b.longerTitle(a));Show the solutionHide the solution
- Step 1:
ais "Ripple" at 215 seconds;bis "Glow" at 248 seconds. - Step 2:
a.isLongerThan(b):thisisa, so it checks215 > 248, which isfalse. - Step 3:
a.longerTitle(b):thisisaandotherisb. It callsb.isLongerThan(a), which checks248 > 215:true. So it returnsother.title, "Glow". - Step 4:
b.longerTitle(a): nowthisisbandotherisa. It callsa.isLongerThan(b), which isfalse, so it returns its owntitle, "Glow".
Answer: Three lines:
false,Glow,Glow. - Step 1:
- Example 2
this in a static method
Why doesn't this compile?
public class Song { private int seconds; public static int getSeconds() { return this.seconds; } }Show the solutionHide the solution
- Step 1:
getSecondsis declaredstatic, so it's called on the class, asSong.getSeconds(), not on a particular song. - Step 2: With no object, there is no current object, so
thishas nothing to refer to. - Step 3: The fix is to remove
static, making it an instance method that returns the current song'sseconds.
Answer: Static methods have no
this, sothis.secondsis a compile error there. - Step 1:
Common mistakes
- Writing
title = title;instead ofthis.title = title;when the parameter has the same name. - Losing track of which object
thisrefers to after passingthisto another object's method. Inside each call,thisis the object before the dot. - Using
thisin a static method.
On the exam
- Tracing questions often call a method on one object and pass another, or pass
this. Before each call, write down which object isthisand which is the parameter.
Connected topics
Videos
Check yourself
3 questions on 3.9 this Keyword. Pick an answer to see if you got it, and why.
Consider the following incomplete class.public class Score
{
private int points;
public Score(int points)
{
/* missing code */
}
public int getPoints()
{
return points;
}
}Which of the following can replace /* missing code */ so that new Score(50).getPoints() returns 50?
Consider the following classes.public class Member
{
private String name;
private Club club;
public Member(String name)
{
this.name = name;
}
public void join(Club c)
{
club = c;
c.add(this);
}
public String getName()
{
return name;
}
}
public class Club
{
private String roster = "";
public void add(Member m)
{
roster += m.getName() + ";";
}
public String getRoster()
{
return roster;
}
}What is printed as a result of executing the following code segment?Club chess = new Club();
Member m1 = new Member("Ana");
Member m2 = new Member("Ben");
m2.join(chess);
m1.join(chess);
System.out.println(chess.getRoster());
Inside an instance method, which of the following does the keyword this refer to?
0 of 3 answered