Reputation: 20658
I've read many large projects in OOP, and I notice that a lot of them use this.[variable]
, [ClassName].[staticVariable]
. For example:
public class ABC {
private float mX;
public static float y;
public float getX() {
return this.mX;
}
public float doSomethingWithY() {
return ABC.y;
}
}
And even with Eclipse auto-generated Getters & Setters
feature, it also comes with this.[variable]
, although it's unnecessary, because no local variable is declared there.
Is there any advantage when using these notations, or it's just a code style?
EDIT so some people don't misunderstand. I know what this
and [ClassName].[staticVariable]
stand for. But in this case, it's unnecessary. The question is: Even if it's unnecessary, why do guru coders still add it? When they need to update/fix a huge project, will there be any advantage and disadvantage?
Upvotes: 1
Views: 204
Reputation: 882
Its syntax,if you want to access instance variable of a class use the (reference of the object).(instance variable name) .Like
A a= new A();// for non static class,this for the current object
a.(instance variable name)
// for non static class do the same but use (class name).variable name
Upvotes: 0
Reputation: 13813
Basically with this, you KNOW for sure that you are working with a class attribute, not with a variable created inside the method or maybe received as a parameter.
And also, it helps in case you have a local var with the same name.
And the final reason: readability.
Upvotes: 3
Reputation: 6158
this.? '?' is a member variable, this is a reference to the current object.
see this
Upvotes: 0
Reputation: 3316
For small pieces of code it doesn't matter but sometimes this can happen:
public float getX() { .... int mX = someFunc() ... return mX; }
In this case, the local value is returned instead of the member variable.
You normally want to be explicit and say this.mX
. However, you shouldn't have huge functions anyway.
Upvotes: 0
Reputation: 106351
It's necessary in some circumstances, for example this.
is required when you need to use a member variable rather than a local method parameter of the same name.
It's also necessary for static variables where you need to be specific which class you want to get the static variable from (many classes could define static variables with the same name).
Apart from the necessary cases, it's really a matter of coding style. My recommendation is to use it whenever it helps to resolve potential ambiguity.
Upvotes: 2
Reputation: 13097
In complicated methods, it's sometimes nice to make a distinction between instance variables in this class, and local variables in a particular function. This distinction is immediately obvious when you use "this."
Upvotes: 1