Java Keyword: this
As a reminder, an object is a instance of a class. Classes, and therefore objects, can have all kinds of content but you’re definitely going to see variables (or properties) and methods (or behaviours) in there. These variables can be inside methods (method or local variables) or outside methods (class or object variables).
Setters and Getters
Setters and getters are very common when working with objects. They are methods that allow the setting of variable values and the return of variable values. Let’s have a look at an example:
public class Student { //class variables private String name; private int grade; public void setName(String name) { //local variables name = name; } public String getName(String name) { //local variables return name; } }
Lines 3 and 4 contain class variables for the student’s name and age respectively. These variables are visible to other parts of the same class (or object), very useful if you want to share this data with other methods.
Line 6 contains an argument that will create a string variable called name that will be local to the method setName. This variable is only visible to other parts of that method, it is local to the setName method.
Line 8 assigns the value of the local variable name to a variable called name. The intention was to assign the student’s name to the class variable name so that it can be seen and used by other parts of the class (or object) but actually what it is doing is assigning itself to itself. This is where the keyword this is useful.
Generally speaking, the this keyword is used to refer to the current class or object. When used with a variable, it will instruct Java to refer to a class or object variable rather than a method or local variable – sounds like something we need to solve this problem:
public class Student { //class variables private String name; private int grade; public void setName(String name) { //class variable = local variable this.name = name; } public String getName(String name) { //local variables return name; } }
In the setName method on line 8, the this keyword has been added followed by a dot (.) before the variable name. Now the method argument (or local variable) name is assigned to the class/object variable name (defined on line 3) making it available to all other methods in the class/object.
The same thing can be done with the getName method (lines 11-14). Currently, that method is returning the value of a local variable name which in this case has no value. This can be improved by adding the this keyword (on line 13) to tell Java to return the class/object name variable value that will have been set by the setName method:
public class Student { //class variables private String name; private int grade; public void setName(String name) { //class variable = local variable this.name = name; } public String getName(String name) { //class variable return this.name; } }
Now the setName method returns the class/object variable name.
For completeness, since the getName method does not have a local variable called name, Java will know to return the class/object variable value but it is good practice to use the this keyword to make it very clear what the intention is.
We can test all of this by creating a student object in the main method of the main class and executing the setName and getName methods:
public class StudentRecords { public static void main(String[] args) { Student myStudent = new Student(); myStudent.setName("Andrew"); System.out.println(myStudent.getName()); } }
The output is:
run: Andrew BUILD SUCCESSFUL (total time: 0 seconds)
Constructors
The this keyword can also be used with object constructors. A constructor is a method that facilitate the construction of an object, typically with the data required for the object to be immediately useful. For example, here is a constructor that will create an object that assigns a name and grade to the myStudent object:
public class Student { //class variables private String name; private int grade; //constructor to create a student object //with name and grade attributes public Student(String name, int grade){ this.name = name; this.grade = grade; } public void setName(String name) { //class variable = local variable this.name = name; } public String getName() { //class variable return this.name; } }
The constructor (lines 8 to 11) requires a name (string) and grade (int) to successfully create on object. For completeness, here is an updated main method with the required constructor arguments (line 4 below):
public class StudentRecords { public static void main(String[] args) { Student myStudent = new Student("Andrew", 89); System.out.println(myStudent.getName()); System.out.println(myStudent.getGrade()); } }
Now the constructor is passed the name and grade required by the object, which will be stored in the appropriate object variables.
Non-Static Methods
Static methods are those that do not require the creation of an object to a accessed. They belong to the class, not the object of a class.
This this keywork can only be used in non-static methods. If you try to use this in a static method your code will not compile. For example, let’s add a static method called getGrade to return the student grade:
public class Student { //class variables private String name; private int grade; public Student(String name, int grade){ this.name = name; this.grade = grade; } public void setName(String name) { //class variable = local variable this.name = name; } public String getName() { //class variable return this.name; } public static int getGrade(){ return this.grade; //causes an error } }
The static method (lines 21-23) itself does not throw an error, but when there is an attempt to access the object variable name using the this keyword (line 22) the following error is reported: “non-static variable grade cannot be referenced from a static context“.
Constructor to Constructor
Another way to use the this keyword is to call a constructor from another constructor. This arrangement is useful if there is a need to have a default set of values if none are provided when the object is created. For example. let’s add a no argument constructor (called Student) that calls the original constructor (also called Student) using the this keyword (line 8 below):
public class Student { //class variables private String name; private int grade; //constructor calling another constructor public Student(){ this("Student", 0); } //constructor public Student(String name, int grade){ this.name = name; this.grade = grade; } public void setName(String name) { //class variable = local variable this.name = name; } public String getName() { //class variable return this.name; } }
As long as the constructor call using the this keyword is the first line of the no argument constructor, Java will understand that it is creating an object using the constructor that matches the arguments provided after the this keyword (namely: this(“Student”, 0)).