I created a class that can find the distance between two points and the value of the midpoint between them:
public class Point {
private double x;
private double y;
public Point (double x, double y) {
this.x = x;
this.y = y;
}
public double getX() {
return x;
}
public void setX(double x) {
this.x = x;
}
public double getY() {
return y;
}
public void setY(double y) {
this.y = y;
}
public static void main (String[] args) {
Point p1 = new Point(1,1);
Point p2 = new Point(4,5);
System.out.println("The distance between p1 and p2 is: " + distance(p1, p2));
System.out.println("The midpoint of p1 and p2 is: " + findMidpoint(p1, p2));
}
public static double distance(Point p1, Point p2) {
return Math.sqrt((p1.getX() - p2.getX()) * (p1.getX() - p2.getX()) +
(p1.getY() - p2.getY()) * (p1.getY() - p2.getY()));
}
public static Point findMidpoint (Point p1, Point p2) {
return new Point((p1.getX() + p2.getX()) / 2, (p1.getY() + p2.getY()) / 2);
}
}
This code compiles fine but when I run it, it gives the output:
The distance between p1 and p2 is: 5.0
The midpoint of p1 and p2 is: Point@15db9742
It gives the same value for the midpoint regardless of the values of p1 and p2. I want to output the midpoint in the format "(x,y)".
Could somebody also explain why I was forced to make the distance and findMidpoint methods static?
Why do I get the same output each time?
Because you're not overriding the
toString
method. The value you're seeing is java's implementation oftoString
. Every object has this behavior.Put this method in your point class to override java's
toString
implementation.This will give you output in the format
(x, y)
as you requested.Why are midpoint and distance static?
The methods being static was a design decision. They could be written to be non-static, but it would make less sense as the methods don't change the state of either point object involved.