3.9 this Keyword
From CS Awesome 2CC BY-NC-SA 4.0Original page
Java1 class period3 exercises8 graded tests
Files
3.9 this Keyword
Each coding exercise has its own folder. Open its .java file and press Run to try it. Run Tests checks every graded exercise in this lesson at once.
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.
For example, in the following Class Person, when we create an object p1 and call the constructor or p1.setEmail(), the word “this” refers to p1. And when we make the same method calls with object p2, “this” refers to p2.
The this variable can only be used in instance methods and constructors. Class methods cannot refer to this or instance variables because they are called with the classname, not an object, so there is no this object.
Exercise 1
Observe the use of the keyword this in the code.
Open the
01-PersonClassThisfolder and runPerson.java. It is an example, so it has no tests.
this.instanceVariable
The keyword this is sometimes used by programmers to distinguish between variables. Programmers can give the parameter variables the same names as the instance variables and this can distinguish them and avoid a naming conflict. For example, both the instance variable and the parameter variable are called name in the code below, but name on its own looks for the closest local variable, the parameter variable, whereas this.name refers to this object's instance variable.
this.instanceVariablecan be used to distinguish between this object’s instance variables and local parameter variables that may have the same variable names.
// instance variables
private String name;
// constructor
public Person(String name)
{
// Set this object's instance variable name to the parameter variable name
this.name = name;
}
this as an Argument
The this variable can be used anywhere you would use an object variable. You can even pass it to another method as an argument. Consider the classes below, Pay and Overtime. The Pay class declares an Overtime object and passes in this (the current Pay object) to its constructor which computes the overtime with respect to that Pay object. Here is an image that shows how this, myPay and p all refer to the same object in memory.

Exercise 2
What does this code print out? Notice how the this Pay object is passed to the Overtime constructor.
Open the
02-PayClassThisfolder and runPay.java. It is an example, so it has no tests.
Check your understanding: Consider the following class definitions.
public class Pay { private double pay; public Pay(double p) { pay = p; } public double getPay() { return pay; } public void calculatePayWithOvertime() { // this Pay object is passed to the Overtime constructor Overtime ot = new Overtime(this); pay = ot.getOvertimePay(); } } public class Overtime { private double payWithOvertime; public Overtime(Pay p) { payWithOvertime = p.getPay() * 1.5; } public double getOvertimePay() { return payWithOvertime; } }The following code segment appears in a class other than Pay or Overtime.
Pay one = new Pay(20.0); one.calculatePayWithOvertime(); System.out.println(one.getPay());What, if anything, is printed as a result of executing the code segment?
Answer it on CS Awesome: https://runestone.academy/ns/books/published/csawesome2/topic-3-9-this.html#AP-this-arg
Coding Challenge: Bank Account

Many people keep their money in a bank account. The bank may keep track of the account holder’s name, the acount balance which is the amount of money in the account, and assign an account number to each account. At the bank or an ATM (automatic teller machine) or on a phone app, the account holder can deposit (add) or withdraw (subtract) an amount from their account. Here’s a video that shows the steps to use an ATM to withdraw money from a bank acount. Phone apps like Venmo and Paypal connect to your bank account or credit card to send and get money from businesses or friends.
For this challenge, you can work in pairs to:
- Create a class called BankAccount below that keeps track of the account holder’s name, the account number, and the balance in the account. Make sure you use the appropriate data types for these.
- Write 2 constructors for the class: one that initializes all the instance variables and one that only has 2 parameters for the name and account number and initializes the balance to 0. For the parameters, use the same variable names as your instance variables. Use the
thiskeyword to distinguish between the instance variables and the parameter variables. - Write a
toStringmethod for the class. Use thethiskeyword to return the instance variables. - Write
withdraw(amount)anddeposit(amount)methods for the class. Thewithdrawmethod should subtract the amount from the balance as long as there is enough money in the account (the balance is larger than the amount). Anddepositshould add the amount to the balance. Use thethiskeyword to refer to the balance. - Test your class below with a
mainmethod that creates aBankAccountobject and calls itsdepositandwithdrawmethods and prints out the object to test itstoStringmethod.
Exercise 3
Create a class called BankAccount that keeps track of the account holder’s name, the account number, and the balance in the account. Create 2 constructors using this (one constructor to initialize all 3 instance variables and one that only has 2 parameters for the name and account number and initializes the balance to 0), a toString() method, and withdraw(amount) and deposit(amount) methods. Test your class in a main method.
Open the
03-challenge-BankAccountfolder and editBankAccount.java. Press Run to try it; Run Tests checks it (8 tests).
Summary
- (AP 3.9.A.1) Within an instance method or a constructor, the keyword
thisacts as a special variable that holds a reference to the current object—the object whose method or constructor is being called. this.instanceVariablecan be used to distinguish between this object’s instance variables and local parameter variables that may have the same variable names.- (AP 3.9.A.2) The keyword
thiscan be used to pass the current object as an argument in a method call. - (AP 3.9.A.3) Class methods do not have a
thisreference.
AP Practice
Check your understanding: Consider the following class definitions.
public class Liquid { private int currentTemp; public Liquid(int ct) { currentTemp = ct; } public int getCurrentTemp() { return currentTemp; } public void addToJar(LiquidJar j) { j.addLiquid(this); } } public class LiquidJar { private int totalTemp; public LiquidJar() { totalTemp = 0; } public void addLiquid(Liquid l) { totalTemp += l.getCurrentTemp(); } public int getTotalTemp() { return totalTemp; } // Constructor not shown. }Consider the following code segment, which appears in a class other than Liquid or LiquidJar.
Liquid water = new Liquid(50); Liquid milk = new Liquid(15); LiquidJar j = new LiquidJar(); water.addToJar(j); milk.addToJar(j); System.out.println(j.getTotalTemp());What, if anything, is printed out after the execution of the code segment?
Answer it on CS Awesome: https://runestone.academy/ns/books/published/csawesome2/topic-3-9-this.html#AP-this
For teachers
3.9 this Keyword
Students read CSAwesome2's “this Keyword” in CS Room and work through its 3 Java coding exercises (1 graded, 2 examples).
- Time: 1 class period
- Tests: 8 in 1 graded exercise, set up for you when you import the lesson
Goals
- (AP 3.9.A.1) Within an instance method or a constructor, the keyword
thisacts as a special variable that holds a reference to the current object—the object whose method or constructor is being called. - (AP 3.9.A.2) The keyword
thiscan be used to pass the current object as an argument in a method call. - (AP 3.9.A.3) Class methods do not have a
thisreference.
Before class
- Import the lesson into your class from the Lessons page, or with New assignment → Use a lesson. It arrives as a draft with its tests already set up.
- Publish it.
- The original page, with its multiple-choice questions, is on CS Awesome: https://runestone.academy/ns/books/published/csawesome2/topic-3-9-this.html
- CS Awesome's own teacher materials: the CS Awesome teacher site
In class
- Students read
README.md. Questions that need CS Awesome's interactive widgets link back to it. - Students do exercises 01–03, each in its own folder, pressing Run to try their code.
- Run Tests checks every graded exercise at once; scores appear in the Gradebook. Grading uses your copy of the tests, so a student who edits theirs does not change the grade.
After class
This lesson ends the section for the College Board Unit 3 part 2. You should now do the review and practice lessons at the end of this unit and then do the College Board Progress Check for Unit 3 Part B and the Virtual Pet Lab in the AP Classroom.
Exercises
| Folder | File | Grading | Tests |
|---|---|---|---|
01-PersonClassThis | Person.java | Example, not graded | 0 |
02-PayClassThis | Pay.java | Example, not graded | 0 |
03-challenge-BankAccount | BankAccount.java | Autograded | 8 |
Teachers can download a reference solution after signing in.