i just say some using "this." in setter, getter and constructor method. i have never done this so is this good prative to use "this" in getter or setter.


public test(int ix)
  this.x = ix;


public int getX()
return this.x;

Edited by game06

5 Years
Discussion Span
Last Post by stultuske

no. that would be static. this refers to "this" instance (the one you are working in) of the class.
this is also why you can't use the this keyword in a static method.

in the examples you've shown, using the this keyword is not very important, but, let's say that both the instance variable and the parameter have the same name:

private String input;

public void setInput(String input){
  input = input;

logic dictates that the value of the instance variable input is set to the value that is passed as parameter, and when we now use a getInput() method, we get what we won't, but no.

in the setter method you are only overwriting the value of the local input variable with it's own value. pretty pointless. it's the same as if one had written:

private String inputA;

public void setInput(String inputB){
  inputB = inputB;

at least here it is clear, since both variables don't have the same name. the this keyword can be used to tell the JVM exactly which variable needs to be updated.

private String input;

public void setInput(String input){
  this.input = input;

since we used the keyword this, the JVM now knows it needs to update the value of the instance variable input, and not the local variable.

This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.