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.

3.9.A3.9.A.13.9.A.23.9.A.3

Reviewed against the CED on

Know this already? Jump to the checkpoint.

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

  1. In an instance method or constructor, this holds a reference to the current object.
  2. The current object is the object whose method or constructor is being called.
  3. this.variable names the instance variable, even when a parameter has the same name.
  4. this can be passed as an argument to give another method a reference to the current object.
  5. 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.

  1. 1 Consider the following class. The code segment below the class appears in a method in another class. What is printed as a result of executing the code segment? 3.9.A.1
    public class Score
    {
        private int points;
    
        public Score(int points)
        {
            this.points = points;
        }
    
        public void add(int points)
        {
            this.points += points * 2;
        }
    
        public int getPoints()
        {
            return points;
        }
    }
    
    Score s = new Score(4);
    s.add(3);
    System.out.println(s.getPoints());
    Show answer

    Answer: B. In the constructor, this.points is the instance variable and points is the parameter, so the object starts with 4. In add, this.points += points * 2 adds 3 * 2 = 6 to the instance variable, giving 10. The option 7 ignores the * 2, 4 assumes add changed only the parameter, and 14 doubles the wrong value.

  2. 2 Consider the following class. The code segment below the class appears in a method in another class. What is printed as a result of executing the code segment? 3.9.A.1
    public class Token
    {
        private int value;
    
        public Token(int value)
        {
            this.value = value;
        }
    
        public boolean matches(Token other)
        {
            return this == other || this.value == other.value;
        }
    }
    
    Token a = new Token(5);
    Token b = new Token(5);
    Token c = new Token(7);
    Token d = c;
    System.out.println(a.matches(b) + " " + c.matches(d) + " " + a.matches(c));
    Show answer

    Answer: D. In a.matches(b), this and other are different objects, but both values are 5, so the result is true. In c.matches(d), this and other refer to the same object, so this == other is true. In a.matches(c) the objects and the values (5 and 7) differ, so it is false. The option false true false forgets the value comparison after ||.

  3. 3 Consider the following class. The code segment below the class appears in a method in another class. What is printed as a result of executing the code segment? 3.9.A.2
    public class Player
    {
        private String name;
        private Player partner;
    
        public Player(String name)
        {
            this.name = name;
        }
    
        public void setPartner(Player p)
        {
            partner = p;
        }
    
        public void pairWith(Player other)
        {
            partner = other;
            other.setPartner(this);
        }
    
        public String partnerName()
        {
            if (partner == null)
            {
                return "none";
            }
            return partner.name;
        }
    }
    
    Player x = new Player("Ana");
    Player y = new Player("Ben");
    Player z = new Player("Cy");
    x.pairWith(y);
    System.out.println(y.partnerName() + " " + x.partnerName() + " " + z.partnerName());
    Show answer

    Answer: A. During x.pairWith(y), this refers to Ana. Ana's partner becomes Ben, and other.setPartner(this) passes the current object, Ana, to Ben, so Ben's partner is Ana. Cy was never paired, so its partner is still null and "none" is printed. The option Ben Ben none treats this as if it meant other, and none Ben none ignores the call to setPartner.

  4. 4 A Lamp class contains the following four members. In which one would using the keyword this cause a compile-time error? 3.9.A.3
    Show answer

    Answer: C. Class methods do not have a this reference, because they are called on the class and not on an object. Constructors and instance methods, including accessors, always run for a current object, so this is available in all of them.

  5. 5 Consider the following incomplete class. The constructor is intended to store its parameters in the instance variables with the same names. Which of the following can replace /* missing code */ so that the constructor works as intended? 3.9.A.1
    public class Movie
    {
        private String title;
        private int minutes;
    
        public Movie(String title, int minutes)
        {
            /* missing code */
        }
    
        public String info()
        {
            return title + " " + minutes;
        }
    }
    Show answer

    Answer: B. this.title and this.minutes name the current object's instance variables, and the plain names mean the parameters, so the key copies each parameter into the object. Without this, each parameter is assigned to itself. title = this.title copies the default value into the parameter, and this.title = this.title leaves the title null while setting only the minutes.

3PrevailLock it in for exam day

By the numbers

Name each list from memory, then reveal it to check. Each list shows how many items to recall.

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
  • Objecttap to flip

    A specific instance of a class with defined attributes.

    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.

Was this page helpful?

No names are ever shown, and every public comment is checked by us first. Please do not include personal details. To get a reply, email [email protected].

↑ Top

Enlarged view of the selected figure