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.
ex:
public test(int ix)
{
this.x = ix;
}
or
public int getX()
{
return this.x;
}
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.
ex:
public test(int ix)
{
this.x = ix;
}
or
public int getX()
{
return this.x;
}
that depends. first of all, do you know what the 'this' keyword refers to?
i think its this class.
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.
We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.