Should I use Point.x or Point.getX()?

Evorlor picture Evorlor · May 13, 2015 · Viewed 7.3k times · Source

I have a Point. I am trying to get x as an int. If I use Point.x, I will get x as an int. But I am under the impression that I should be using a getter whenever possible (Why use getters and setters?). The issue with Point.getX() is that it returns a double instead of an int.

Which is better, or is it just preference?

a or b?

Point point = new Point(5, 5);
int a = point.x;
int b = (int) point.getX();

I have read Java Point, difference between getX() and point.x, but it did not really answer my question. Or at least I did not understand the answer.

Answer

Kevin Workman picture Kevin Workman · May 13, 2015

The getX() and getY() functions of the Point class return a double because that's what its parent class (Point2D) requires. This is so all of its subclasses (Point2D.Double and Point2D.Float) will all work in the same places.

Using point.x and point.y directly instead of using the getter functions is probably fine in this case, since the Point class is a weird corner case that nobody seems to love- most people think it should be immutable, or at least better hide its values.

If you're afraid of something like a code review, just throw a comment in there explaining why you're accessing the x and y variables directly.

tl;dr: it just comes down to personal preference.