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.
distance(Point2D p) Calculates the distance between this point and point p. equals(java.lang.Object obj) Returns whether this object is equal to the specified object or not.
Class Point. A point representing a location in (x,y) coordinate space, specified in integer precision.
If your Point class has a constructor Point(int x, int y) , then you can read both coordinates from the Scanner and create Point from them: int x = sc. nextInt(); int y = sc. nextInt(); Point coordinates = new Point(x, y);
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With