The this Keyword
How an object refers to itself: this as a reference to the current object, using it to reach instance variables hidden by parameters, passing the current object to other methods, and why class methods have no this.
Within 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. It lets code name the object's own instance variables explicitly, compare the object with others, and pass the object itself as an argument in a method call. Class methods are not called on any object, so class methods do not have a this reference.
1The Current Object
Every call to an instance method is made on some object: in a.area(), that object is the box that a refers to. Within the method, the keyword this holds a reference to that object. The same method code runs for every box, and this is what connects each run to the particular object it is working on.
In a constructor, this refers to the object being created. this cannot be assigned a new value; it is set automatically for each call. Like any reference, it can be used with the dot operator to reach instance variables and methods, compared with ==, or passed as an argument.
A helpful way to picture it: every instance method behaves as if it had a hidden extra parameter named this, filled in with the object before the dot. Calling k.toggle() and then h.toggle() runs the same code twice with two different values of this, which is why each light keeps its own state.
this acts as a special variable that holds a reference to the current object.| Where | Does this exist? | What it refers to |
|---|---|---|
| Constructor | Yes | The object being created |
| Instance method | Yes | The object the method was called on |
| Class method (static) | No | Using it does not compile |
Which Light Is this?
Predict the output.
public class Light
{
private String room;
private boolean on;
public Light(String room)
{
this.room = room;
this.on = false;
}
public void toggle()
{
this.on = !this.on;
System.out.println(this.room + " " + this.on);
}
}
kitchen true
hall true
kitchen false
- 1
k.toggle().thisis the kitchen light: off becomes on. - 2
h.toggle().thisis now the hall light, a different object with its ownon. - 3
k.toggle()again. Back to the kitchen light, which turns off.
this to the object before the dot, so one method body serves every object.2this and Shadowing
When a parameter or local variable has the same name as an instance variable, the plain name refers to the local one. this. reaches past it: this.width always means the current object's instance variable. This makes it possible to give constructor parameters the natural names of the attributes they initialize, as in this.width = width;.
The alternative is to give parameters different names, such as w. Both styles are correct and common. What matters is that the instance variable is actually assigned; width = width; without this. compiles but changes nothing.
this. names the instance variable of the current object.Inside the constructor Box(int width, int height) | Refers to |
|---|---|
width | The parameter |
this.width | The instance variable of the new box |
this | The new box itself |
Parameters Named Like Instance Variables
The constructor's parameters share names with the instance variables, and this. tells them apart. Predict the output.
public class Box
{
private int width;
private int height;
public Box(int width, int height)
{
this.width = width;
this.height = height;
}
public int area()
{
return width * height;
}
public boolean isLargerThan(Box other)
{
return this.area() > other.area();
}
public boolean isSameBoxAs(Box other)
{
return this == other;
}
}
12
10
- 1
this.width = width;stores the parameterwidthin the instance variablewidthof the object being constructed. - 2Each object gets its own values: 3 × 4 = 12 and 5 × 2 = 10.
- 3Without
this.,width = width;would assign the parameter to itself and leave the instance variable at 0.
this refers to the object being created, so this.width is its instance variable even when a parameter has the same name.In a constructor whose parameter is named like an instance variable, width = width; assigns the parameter to itself, and the object's width stays 0. Write this.width = width;, or rename the parameter.
3this With Other Objects of the Same Class
Methods that compare or combine two objects often use this for one and a parameter for the other. In a.isLargerThan(b), this is a's box and other is b's, so this.area() > other.area() compares them. Writing this. is optional here, but it makes the symmetry between the two objects easy to see.
this can also be compared with another reference: this == other is true exactly when the parameter refers to the very object the method was called on. That test distinguishes "the same object" from "a different object with the same data."
Comparing the Current Object With a Parameter
Predict the output.
public class Box
{
private int width;
private int height;
public Box(int width, int height)
{
this.width = width;
this.height = height;
}
public int area()
{
return width * height;
}
public boolean isLargerThan(Box other)
{
return this.area() > other.area();
}
public boolean isSameBoxAs(Box other)
{
return this == other;
}
}
true
false
true
false
- 1
a.isLargerThan(b). Inside the call,thisisa's box (area 12) andotherisb's (area 10):true. - 2
b.isLargerThan(a). Nowthisisb's box: 10 > 12 isfalse. - 3
a.isSameBoxAs(c).this == othercompares references;cis an alias ofa:true. - 4
a.isSameBoxAs(b). Different objects:false.
this refers to whichever object the method was called on, so the same code compares different pairs depending on the call.Copying Another Box's Dimensions
Predict the output.
public class Box
{
private int width;
private int height;
public Box(int width, int height)
{
this.width = width;
this.height = height;
}
public void copyFrom(Box other)
{
this.width = other.width;
this.height = other.height;
}
public int area()
{
return width * height;
}
}
42 42
false
- 1Inside
small.copyFrom(big),thisissmallandotherisbig. - 2Same-class access.
other.widthis private, butcopyFromis written insideBox, so it may read it. - 3Copies, not aliases. Both boxes now have area 42, yet they are still two separate objects:
small == bigisfalse.
this names the object receiving the values and the parameter names the source, which keeps the direction of the copy unmistakable.In b.isLargerThan(a), this is b, not a. Always identify which object is before the dot in the call; that object is this for the whole method.
4Passing the Current Object as an Argument
The keyword this can be used to pass the current object as an argument in a method call. When a member joins a team, the member's join method can call t.add(this), handing the team a reference to the member itself. The team then receives the same object that join was called on.
This pattern lets objects register themselves with other objects, report themselves to a manager, or compare themselves using another class's method. As with any reference passed to a method, the receiving method gets a copy of the reference, so it can use, and possibly change, the same object.
Passing this is also useful when an object needs to use a method written for its class in another place, such as a class method that compares two objects: inside an instance method, Box.larger(this, other) passes the current box as the first argument. Wherever a reference to "me" is needed, this supplies it.
this can be used to pass the current object as an argument in a method call.An Object Introducing Itself
A member joins a team by passing itself to the team. Predict the output.
public class Team
{
private int count;
private String lastJoined;
public Team()
{
count = 0;
lastJoined = "nobody";
}
public void add(Member m)
{
count++;
lastJoined = m.getName();
}
public String status()
{
return count + " members, last: " + lastJoined;
}
}
public class Member
{
private String name;
public Member(String name)
{
this.name = name;
}
public String getName()
{
return name;
}
public void join(Team t)
{
t.add(this);
}
}
2 members, last: Odile
- 1
p.join(t). Insidejoin,thisis the member "Rafe";t.add(this)passes that member to the team. - 2
q.join(t)does the same for "Odile". - 3The team counted two members, and the last one added was Odile.
this can be used to pass the current object as an argument in a method call.5Implicit this
Inside an instance method, using an instance variable's name alone, or calling another instance method by name alone, implicitly uses the current object. liters means this.liters, and spaceLeft() means this.spaceLeft(), unless a local variable with the same name shadows it.
Programmers usually leave this. out when there is no ambiguity and write it when it adds clarity: in constructors with matching parameter names, or in methods that work with two objects of the same class. Either way, understanding that the current object is always involved explains how instance methods reach the right data.
| Use of this | Example | Meaning |
|---|---|---|
| Name an instance variable | this.width = width; | The current object's width, not the parameter |
| Call a method on the current object | this.area() | Same as area() inside an instance method |
| Pass the current object | t.add(this); | Give another object a reference to this one |
| Compare with another reference | this == other | Are they the same object? |
Calling Another Method on the Same Object
Inside an instance method, calling another instance method by name calls it on the current object. Predict the output.
public class Tank
{
private int liters;
private int capacity;
public Tank(int capacity)
{
this.capacity = capacity;
liters = 0;
}
public int spaceLeft()
{
return capacity - liters;
}
public void fillUp()
{
liters = liters + spaceLeft();
}
public int getLiters()
{
return liters;
}
}
60
- 1
spaceLeft()insidefillUpmeansthis.spaceLeft(): it runs on the same tank. - 2Result. Space left is 60 − 0 = 60, so the tank fills to 60.
this. were written in front.Inside an instance method, spaceLeft() is not a free-standing call; it runs on the current object, the same one the outer method was called on. Its result depends on that object's state.
6Class Methods Have No this
Class methods do not have a this reference. A static method is called on the class, as in Box.describe(), not on any box, so there is no current object for this to refer to. Using this, or an instance variable or instance method that would implicitly use it, inside a static method does not compile.
This is the same rule seen from another angle: class methods cannot reach instance data without being given an object. If a static method needs an object, it must receive one as a parameter and use that parameter's name instead of this.
When converting an instance method into a class method, therefore, every use of this, written or implied, must be replaced by a parameter. When converting the other way, a parameter that always receives "the object being worked on" can usually become this, and the method can be called on that object directly.
this reference, because they are not called on any particular object.Using this Inside a static Method
Explain the compile error.
public class Box
{
private int width;
public Box(int width)
{
this.width = width;
}
public static int describe()
{
return this.width;
}
}
- 1
describeis a class method. It is called on the class, not on any box. - 2There is no current object, so
thishas nothing to refer to, and the compiler rejects it. - 3Fix. Make
describean instance method, or give it aBoxparameter and use that.
this reference.main is a static method, so this does not exist there. To work with an object in main, create it with new and use the variable that refers to it.
Four Habits for this
1. this = The Object Before the Dot
Or the object being constructed.
2. this.field Beats Shadowing
Use it when a parameter shares the name.
3. Pass this to Share Yourself
t.add(this) hands over a reference.
4. No this in static Code
Class methods have no current object.
Within 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. It can name the current object's instance variables when they are shadowed, call its methods, be compared with other references, and be used to pass the current object as an argument in a method call. Class methods do not have a this reference.