Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

java

getter

point

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.

like image 929
Evorlor Avatar asked May 13 '15 15:05

Evorlor


People also ask

What is point to point in Java?

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.

Is there a point class in Java?

Class Point. A point representing a location in (x,y) coordinate space, specified in integer precision.

How do you create a point in Java?

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);


1 Answers

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.

like image 167
Kevin Workman Avatar answered Oct 05 '22 08:10

Kevin Workman