zuai-logo

This Keyword

Caleb Thomas

Caleb Thomas

5 min read

Listen to this study note

Study Guide Overview

This study guide covers the this keyword in Java, including its use for referencing instance variables, as a parameter, and in constructor/method calls. It also demonstrates how to use this to overload constructors and finalize classes with examples using the Assignment and Student classes. The examples show adding overloaded constructors and new methods like newAssignment() and getLetterGrade().

Introduction to This

In the last topic, we posed this scenario:

If there is a local variable (usually a parameter) and a global variable (usually an instance variable) in the same method with the same name, the local variable takes precedence. However, it is convention for our constructor and mutator parameters to have the same names as our instance variables!

Now, we will come up with a way to fix this. This will also give us a way to efficiently overload constructors as well. Once we learn about this, we can finish our classes once and for all! So what is this mysterious strategy?

The answer lies in the this keyword. The this keyword is a keyword that essentially refers to the object that is calling the method or the object that the constructor is trying to make. There are three ways to use this:

  1. To refer to an instance variable This will solve the problem of having duplicate variable names. To distinguish the instance and local variables, we use this.variableName for the instance variable and simply variableName for the local variable.

  2. As a parameter Sometimes, we can also use the object as a parameter in its own method call to use itself in the method by using objectName.methodName(this).

  3. As a constructor or method call This will allow us to overload our constructors effectively. Inside the...