Reputation: 174
private int x;
private int y;
public Point(int x, int y){
this.x = x;
this.y = y;
}
public void setY(int y){
this.y = y;
}
public int getY() {
return y;
}
public void setX(int x){
this.x = x;
}
public int getX() {
return x;
}
I want to implement the Sum method. But I can't seem to find a good practice for using accessors within a class. Which is the better approach for this?
public int sum(){
return x + y;
}
Or
public int sum(){
return getX() + getY();
}
Upvotes: 1
Views: 553
Reputation: 404
You can omit the 'this' as it is clear from context that you are using class variables, just as you have already done in the getters. 'This' in the constructor and setter methods serves to distinguish the class variable from the input parameter where both have the same name.
public int summ(){
x + y;
}
Points to note:
Upvotes: 0
Reputation: 77177
Certainly you can, as you just showed! There's one important distinction in general, though: The methods can be overridden by a subclass, but the field access can't.
There's a guideline that items that aren't intended to be overridden should be made final
, but if you want someone to be able to create a new LoggingPoint extends Point
that prints log messages when it's accessed, then you should usually access the properties through the accessors so that the subclass can override getX()
and getY()
.
(The one exception is in a constructor, where the subclass's initialization might not have run yet. This kind of complication is the reason some people prefer to make everything final by default: You can always "open" a final class later on if extension is needed, but it's difficult to "close" a class that wasn't final.)
Upvotes: 1