0

this keyword in java setters

why is the this keyword in java getters and why aren't they used in getters

10th Dec 2018, 7:45 PM
Ibrahim Adeosun
Ibrahim Adeosun - avatar
4 Respostas
+ 6
Ibrahim Adeosun Here's an example thanks to David Carroll , who explained 'this' so nicely!👍😉 https://code.sololearn.com/c1o7n3XaFXI6/?ref=app
10th Dec 2018, 9:18 PM
Danijel Ivanović
Danijel Ivanović - avatar
+ 4
In Java, 'this' keyword is a reference to the current object whose method is being called. The various usage of keyword 'this' in Java : - It can be used to refer current class instance variable ; - It can be used to invoke or initiate current class constructor ; - It can be passed as an argument in the method call ; - It can be passed as argument in the constructor call ; - It can be used to return the current class instance .
10th Dec 2018, 8:00 PM
Danijel Ivanović
Danijel Ivanović - avatar
+ 3
Ibrahim Adeosun The `this` keyword is optional except when a local variable or parameter in a class method or constructor has the same name as the class field property. In that case, the `this` keyword is required to fully qualify the class field property. You've probably seen examples where a [s]etter for `age` might look like: public void setAge(int age) { this.age = age; } Here, `age` refers to the parameter and `this.age` refers to the class field property. Likewise, the [s]etter could have been written without the `this` keyword as seen here: public void setAge(int myAge) { age = myage; } Or, if the class field property used an underscore as seen here: public void setAge(int age) { _age = age; }
10th Dec 2018, 8:59 PM
David Carroll
David Carroll - avatar
0
Within a non-static method and/or constructor, this is a reference to the currenct object created by JVM. It is used to access static and non-static members. Consider the following example encapsulation public class Main { private String name; private int age; public void setNameAndAge(String name,int a) { this.name=name; age = a; } public String getName(){return name;} public int getAge(){return age;} } As you can see the setter setNameAndAge() has this keyword in the first assignment.This is because the name of non-static variable(i.e. private String name) and the local variable is same. In short, this.name is nothing but "private String name; " and name is the string parameter/local variable of the setter setName(). In the second statement inside the setter, the names are different therefore there is no need of this keyword however you can put it like this.age=a
10th Dec 2018, 9:25 PM
Rishi Anand
Rishi Anand - avatar