Reputation: 15
Is it still needed to use "this." to keep calling a variable in a class? For example:
public class APLine {
private int a;
private int b;
private int c;
public APLine(int a, int b, int c){
this.a = a;
this.b = b;
this.c = c;
}
public double getSlope(){
return (double)this.a * - 1/ this.b;
}
public boolean isOnLine(int x, int y){
return this.a * x + this.b * y + this.c == 0;
}
}
For the methods getSlope() and isOnLine() is it needed to code this.a, this.b, or this.c. Or is it completely unnecessary and it's okay to just use a, b, or c?
Upvotes: 0
Views: 172
Reputation: 16908
Keyword this
refers to the current instance of the class. So in your case it is not necesary to use this.fieldName
as you do not have another variable which is shadowing the instance field.
But consider this scenario where you'd be needing to use this
:
public boolean isOnLine(int a, int b){
return this.a * a + this.b * a + c == 0;
}
Here the local variables a
and b
are shadowing the instance fields a
and b
. If you do not use this
, a
will simply refer to the local variable and not the instance field.
Upvotes: 2