Reputation:
I am doing a project for CS, and I just realized that I do not understand the mechanics behind the this. java reference and getters. Specifically, if I have the following:
class Circle{
private int radius;
}
public Circle(int radius){
this.radius = radius;
}
public int getRadius(){
return radius;
}
Why is it that for the constructor, I use this.radius
to reference the data field "radius" in the Circle class, but for the constructor, I have this.radius = radius
?
Does it make a difference whether or not I use the this. so long as it is the only data field named radius
?
I just tested it on Sublime, and it outputs the same result.
Just according to my own logic, would it not make more sense to use this.radius
to return the radius in the getRadius()
getter instead of just return radius
because I am referring to the data field in the object Circle
?
I really appreciate all the help I can get!
Upvotes: 0
Views: 104
Reputation: 27
Actually when you refer to this.radius
that means you use a class field variable. Otherwise (in your code) you may re-assign your radius
as an argument in a given constructor that is may be unwanted in your case. To distinguish it you must either use different name of a variable or use this
.
Upvotes: 0
Reputation: 201487
You don't need this
in the constructor if you do not shadow the local name. That is with
public Circle(int r){
this.radius = r;
}
You can write
public Circle(int r){
radius = r;
}
The this
is only required when it is used to specify which radius
you are referring to.
Upvotes: 2
Reputation: 26056
It's because radius
is the name of both parameter of constructor and field of the class. To disambiguate those this
keyword is used. In case of getter this
is not needed, but also won't hurt. Some formatters add this
by default, it's equivalent to:
public int getRadius(){
return this.radius;
}
Upvotes: 3