Reputation: 594
I am new to Java. I know about some core basics of Java such as setter and getter and recently came across a getter with a parameter (not sure if it is correct way of calling it):
public double getDistance(Point p)
{
// what is inside here? Usually without the "Point p" I simply put "return distance;"
}
This method belongs to a class called Point and it is meant to get the calculation of distance from a private method in the same class.
I will appreciate if someone can enlighten me on the getter "parameter" and how I can apply the return in this method.
Thank you.
EDIT: Added the private calculation method
// Compute distance
private double distance(Point p)
{
double xx;
double yy;
double r;
xx = this.x - p.x;
yy = this.y - p.y;
r = Math.sqrt(nx * nx + ny * ny);
return r;
}
Upvotes: 0
Views: 2874
Reputation: 40062
Why not use Point2D
? It has built-in methods for computing distances from a supplied point to some point you already have.
Point2D pt = new Point2D.Double(10,20);
double distance = pt.distance(new Point2D.Double(20,30));
System.out.println(distance);
Check it out at java.awt.geom.Point2D
Upvotes: 0
Reputation: 201477
I think a simple argument rename will make things clear, you want to calculate the distance between two-points. Specifically, this
point and that
point. Assuming you have double
x
and y
coordinates in each Point
that might look like,
public double getDistance(Point that) {
double tmpX = that.x - this.x;
double tmpY = that.y - this.y;
return Math.sqrt((tmpX * tmpX) + (tmpY * tmpY));
}
Upvotes: 1