DEV Community

Chhavi Joshi
Chhavi Joshi

Posted on • Edited on

Setter and Getter and "this" keyword in java

We know that we can use access modifiers in java for data security, so when we use private access modifier for attributes, they can not be directly accessed in other class for this we use setter and getter functions.
Consider the following code and its explaination:

Setter function:

This image shows basic syntax of setter function, which is a normal function with return type, parameters and then the action to be performed.
This performs action of initializing value to the attribute name of object.
But there is a tiny detail to pay attention to, in the parameter section of the code I wrote "setName( String n)", that's why at the time of assigning value I could directly write "name = n", if I had written "setName( String name)" instead then I would have used this keyword as in the code given below.

As explained above, since the name of parameter of the function was same as that of the attribute, "this" keyword was used to resolve misinterpretation. As without use of "this" keyword the code would've been :
public void setName(String name){
name = name;
}
and the compiler would not be able to interpret which name suggests the attribute and which suggests parameter.

This code is for default value, i.e. if an object does not have name then this setter would set default value for name.

Getter function:

The getName function performs the action of printing the name.
And if we do not want to necessarily display the value but just return its value , get function with a little different syntax as follows can be used.

This would not print the value but just return the setted value of attribute, and we could later use the print statement to print this as:
System.out.println(emp2.getName());

Main class of code:

Top comments (0)