+ 3

Why there is no "this" keyword in getter methods?

Inside setter methods we use "this" keyword to access the class property, why we don't use it getter methods too ? or opposite?

13th Nov 2016, 10:00 AM
Levon Hakobyan
Levon Hakobyan - avatar
3 Answers
+ 6
because usually the given parameter name is the same as the class variable so 'this' is used to identify which of them belong to the class and which one was passed to the method by default, if no other value has the same name, then it will identify the class variable so there is no need for it it is a good practice tho to use 'this' to prevent mishaps
13th Nov 2016, 10:33 AM
Burey
Burey - avatar
+ 2
this works only when it is clear which object it is. you can use it when point the object itself outside it it is not clear.
13th Nov 2016, 6:58 PM
Sandeep Chatterjee
+ 2
"this" is refering to the reference of the current class/interface there will be some case that you need to specify which variable/method/function you called from the simplest example is on encapsulation, when you declare a setter getter of a variable public class Example{ private int number; public vois setNumber(int number){ this.number = number; //this is refering to Example's number because this method also has a variable named number too } } another case when you want to store the reference of your current class to a variable, like this public claas Example{ private Example instance; public Example(){ instance = this; } } the conculision is, this is refering to the instance of current clasa/interface
14th Nov 2016, 11:06 AM
Raizal I N Pregnanta
Raizal I N Pregnanta - avatar