5.9 this Keyword
As discussed in the previous section, when you use a variable in a method or constructor that shares the same name as an instance variable, by default, the local variable in the method or constructor is used. What if you want to refer to the instance variable?
It can often be confusing to know whether a variable in a constructor is referring to an instance variable or a variable that was passed in as an argument to the constructor. One way around this is to use different variable names for the instance variables and parameters, however using different names can get a little confusing.
Fortunately, Java has a way of specifying when you are referring to the object itself: this
.
this
refers to the current object. The this
keyword allows you to be very clear whether you are referring to the object’s instance variable or a parameter:
Notice in the above example how you can use the same variable name. When the variable name is preceded by this.
, the variable is referring to the instance variable, otherwise it refers to the local variable.
As noted above, the this
keyword is used to represent the current object. With that in mind, you can use this
to represent the current object as needed.
Notice in the example above how the getArea
method is called using this
as an actual parameter for input into the getArea method.
-
Incorrect
Correct
No Answer was selected
Invalid Answer
Which of the following correctly uses the this keyword?
We have constructed an Exercise
Class for you.
The class should have a default constructor that takes no parameter and a constructor that takes three parameters. Complete the body of the constructor that takes three parameters but do not update the constructor heading.