AP Computer Science A · Unit 3 lecture · Part 9 of 10 · 8 min

3.9 this keywordthis: the object that is running

Mr. Thompkins
Every instance method runs on some object, the one in front of the dot. Java gives that object a name you can use inside the method: this. Three small jobs, and you'll use all three.

Inside a constructor or an instance method, this is a reference to the current object. In ben.joinClub(chess), this means ben's object. In ana.older(ben), this means ana's object. You never declare this. Java supplies it automatically every time an instance method or constructor runs.

Job one: telling an instance variable apart from a parameter with the same name. this.name = name; reads "this object's name gets the parameter name". Job two: passing the current object to another method, as in c.addMember(this). Job three: returning the current object, as in return this;.

1public class Student2{3    private String name;4    private int grade;56    public Student(String name, int grade)7    {8        this.name = name;19        this.grade = grade;110    }1112    public void joinClub(Club c)13    {14        c.addMember(this);215    }1617    public Student older(Student other)18    {19        if (other.grade > grade)20        {21            return other;22        }23        return this;324    }2526    public String getName() { return name; }27}
  1. line 8-9 this.name: the variable of the object being built
  2. line 14 Pass the current object to another object's method
  3. line 23 Return a reference to the current object
Student uses this for all three jobs.
1public class Club2{3    private String title;4    private Student first;15    private int members;67    public Club(String title)8    {9        this.title = title;10        members = 0;11    }1213    public void addMember(Student s)14    {15        members++;16        if (first == null)217        {218            first = s;219        }220    }2122    public String summary()23    {24        return title + ": " + members + ", first "25            + first.getName();26    }27}28// in a client class29Club chess = new Club("Chess");30Student ana = new Student("Ana", 11);31Student ben = new Student("Ben", 10);32ben.joinClub(chess);333ana.joinClub(chess);34System.out.println(chess.summary());35System.out.println(ben.older(ana).getName());36System.out.println(ana.older(ben).getName());
  1. line 4 Never assigned in the constructor, so it starts as null
  2. line 16-19 Only the first student to join is kept
  3. line 32 Inside joinClub, this is ben
output › Chess: 2, first Ben Ana Ana
Club keeps a count and a reference to the first student who joined.
benStudent "Ben"this, insideben.joinClub(...)chessClub "Chess"members 1firstc.addMember(this)hands over a referenceto ben's object
During ben.joinClub(chess), this is ben. addMember stores that reference in first.
?Wait, why can't a static method use this?
A static method runs on the class, with no object in front of the dot, so there is no current object for this to mean. Writing this inside a static method is a compile error, for the same reason instance variables are off limits there.
?Wait, what does first == null check?
first is a Student reference that the constructor never assigned, so it starts as null. first == null asks "has nobody been stored here yet?" It's true only for the first member, so only that student is saved.
Pause and think
Two students are both in grade 11: Ana and Cy. What does ana.older(cy).getName() return?
I thought about it. Show me
"Ana". other.grade > grade is 11 > 11, which is false, so older returns this, and this is ana. On a tie, the method keeps the current object. Read the condition exactly: > is not >=.
Trace this
Trace the client code at the bottom of the Club figure and give all three lines of output.
  1. The constructor gives the club the title "Chess", members 0, and first stays null.
  2. ben.joinClub(chess): this is ben, so chess.addMember(ben's object) runs. members becomes 1, and first is null, so first now refers to Ben.
    Why?
    This is job two: this hands the current object to another object's method.
  3. ana.joinClub(chess): members becomes 2. first is not null anymore, so it stays Ben.
  4. summary() builds "Chess: 2, first Ben".
  5. ben.older(ana): other is Ana, 11 > 10 is true, so it returns Ana. ana.older(ben): 10 > 11 is false, so it returns this, which is Ana again.
    Why?
    Job three: return this gives back a reference to the object the method was called on.

Answer: Chess: 2, first Ben, then Ana, then Ana.

Stuck? Get a hint
  1. Write down who this is for each call: it's the variable before the dot.
  2. addMember only saves a student when first is still null.
  3. older returns other only when other's grade is strictly bigger.
Check yourself
What is printed? (Use the Student and Club classes above.)
Club art = new Club("Art");
Student lia = new Student("Lia", 9);
Student max = new Student("Max", 12);
lia.joinClub(art);
max.joinClub(art);
lia.joinClub(art);
System.out.println(art.summary());
  1. AArt: 3, first Lia
  2. BArt: 2, first Lia
  3. CArt: 3, first Max
  4. DArt: 2, first Max
Show the answer

A. Every call to addMember adds 1, even when the same student joins twice, so members is 3. Lia joined first, so first is Lia. The second choice is the trap: nothing in the code checks for repeats.

Exam tip from Mr. T

Whenever a constructor's parameters have the same names as the instance variables, write this. in front of every instance variable. It costs four characters and saves the constructor point.

  • this is a reference to the object whose method or constructor is running.
  • this.x = x; assigns the parameter x to the instance variable x.
  • c.addMember(this) passes the current object; return this; returns it.
  • Static methods have no this.