---
title: "The this Keyword | FiveStudy"
description: "Shadowing, the this.x = x idiom, the reversed accident, and scope-ring lookup order."
url: https://fivestudy.com/guides/this-keyword
---

[AP Computer Science A](https://fivestudy.com/ap-computer-science-a) · Study guide

# The this Keyword

[Figure: FiveStudy]

FiveStudy

AP® Computer Science A · Class Creation

AP® Computer Science A · Class Creation

# 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.

1. The Current Object 2. this and Shadowing 3. this With Other Objects 4. Passing this 5. Implicit this 6. No this in Class Methods

Big Picture

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.

## 1 The 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.

**Figure 1.** Within an instance method or a constructor, the keyword `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 |

Worked Example 1 this changes with each call

### Which Light Is this?

Predict the output.

A Light class

```
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);
    }
}
```

Output

```
kitchen true
hall true
kitchen false
```

1. 1 **`k.toggle()`.** `this` is the kitchen light: off becomes on.
2. 2 **`h.toggle()`.** `this` is now the hall light, a different object with its own `on`.
3. 3 **`k.toggle()` again.** Back to the kitchen light, which turns off.

**Result:** The output is kitchen true, hall true, kitchen false. Each call sets `this` to the object before the dot, so one method body serves every object.

## 2 this 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.

**Figure 2.** When a parameter shadows an instance variable, `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 |

Worked Example 2 this in a constructor

### Parameters Named Like Instance Variables

The constructor's parameters share names with the instance variables, and `this.` tells them apart. Predict the output.

The Box class and a short program

```
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;
    }
}
```

Output

```
12
10
```

1. 1 **`this.width = width;`** stores the parameter `width` in the instance variable `width` of the object being constructed.
2. 2 **Each object gets its own values:** 3 × 4 = 12 and 5 × 2 = 10.
3. 3 **Without `this.`**, `width = width;` would assign the parameter to itself and leave the instance variable at 0.

**Result:** The output is 12 and 10. Within a constructor, `this` refers to the object being created, so `this.width` is its instance variable even when a parameter has the same name.

Common Mistake 1 · Forgetting this. When Names Match

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.

## 3 this 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."

Worked Example 3 this and another object

### Comparing the Current Object With a Parameter

Predict the output.

Using the same Box class

```
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;
    }
}
```

Output

```
true
false
true
false
```

1. 1 **`a.isLargerThan(b)`.** Inside the call, `this` is `a`'s box (area 12) and `other` is `b`'s (area 10): `true`.
2. 2 **`b.isLargerThan(a)`.** Now `this` is `b`'s box: 10 > 12 is `false`.
3. 3 **`a.isSameBoxAs(c)`.** `this == other` compares references; `c` is an alias of `a`: `true`.
4. 4 **`a.isSameBoxAs(b)`.** Different objects: `false`.

**Result:** The output is true, false, true, false. `this` refers to whichever object the method was called on, so the same code compares different pairs depending on the call.

Worked Example 4 this and a same-class parameter

### Copying Another Box's Dimensions

Predict the output.

A Box class with copyFrom

```
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;
    }
}
```

Output

```
42 42
false
```

1. 1 **Inside `small.copyFrom(big)`,** `this` is `small` and `other` is `big`.
2. 2 **Same-class access.** `other.width` is private, but `copyFrom` is written inside `Box`, so it may read it.
3. 3 **Copies, not aliases.** Both boxes now have area 42, yet they are still two separate objects: `small == big` is `false`.

**Result:** The output is 42 42, then false. `this` names the object receiving the values and the parameter names the source, which keeps the direction of the copy unmistakable.

Common Mistake 2 · Mixing Up this and the Parameter

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.

## 4 Passing 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.

**Figure 3.** The keyword `this` can be used to pass the current object as an argument in a method call.

Worked Example 5 Passing this

### An Object Introducing Itself

A member joins a team by passing itself to the team. Predict the output.

Team and Member classes and a short program

```
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);
    }
}
```

Output

```
2 members, last: Odile
```

1. 1 **`p.join(t)`.** Inside `join`, `this` is the member "Rafe"; `t.add(this)` passes that member to the team.
2. 2 **`q.join(t)`** does the same for "Odile".
3. 3 **The team** counted two members, and the last one added was Odile.

**Result:** The output is 2 members, last: Odile. The keyword `this` can be used to pass the current object as an argument in a method call.

## 5 Implicit 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? |

Worked Example 6 Implicit this

### 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.

A Tank class

```
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;
    }
}
```

Output

```
60
```

1. 1 **`spaceLeft()` inside `fillUp`** means `this.spaceLeft()`: it runs on the same tank.
2. 2 **Result.** Space left is 60 − 0 = 60, so the tank fills to 60.

**Result:** The output is 60. Writing an instance method's name alone inside another instance method calls it on the current object, exactly as if `this.` were written in front.

Common Mistake 3 · Thinking a Method Call Without a Dot Has No Object

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.

## 6 Class 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.

**Figure 4.** Class methods do not have a `this` reference, because they are not called on any particular object.

Worked Example 7 No this in class methods

### Using this Inside a static Method

Explain the compile error.

Code that does not compile

```
public class Box
{
    private int width;

    public Box(int width)
    {
        this.width = width;
    }

    public static int describe()
    {
        return this.width;
    }
}
```

1. 1 **`describe` is a class method.** It is called on the class, not on any box.
2. 2 **There is no current object**, so `this` has nothing to refer to, and the compiler rejects it.
3. 3 **Fix.** Make `describe` an instance method, or give it a `Box` parameter and use that.

**Result:** The code does not compile. Class methods do not have a `this` reference.

Common Mistake 4 · Using this in main

`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.

Core Synthesis

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.

FiveStudy AP® Computer Science A Study Guide · Class Creation · The this Keyword Back to top ↑
