In: Computer Science
Design a class named MyPoint to represent a point with x- and y-coordinates. The class should contain:
Two data fields x and y that represent the coordinates.
A no-arg constructor that creates a point at (0, 0).
A constructor that creates a point with specified coordinates.
Get methods for data fields x and y respectively.
A method named distance that returns the distance from this point to another point with specified x- and y-coordinates. Use the formula: root (x2-x1)2 + (y2-y1)2
public class MyPoint {
private double x, y;
public MyPoint() {
this.x = 0;
this.y = 0;
}
public MyPoint(double x, double y) {
this.x = x;
this.y = y;
}
public double getX() {
return x;
}
public double getY() {
return y;
}
public double distance(MyPoint point) {
return Math.sqrt(Math.pow(x - point.x, 2) + Math.pow(y - point.y, 2));
}
@Override
public String toString() {
return "(" + x + ", " + y + ")";
}
}
class PointTest {
public static void main(String[] args) {
MyPoint first = new MyPoint();
MyPoint second = new MyPoint(10, 30.5);
System.out.printf("The distance between " + first + " and " + second + " is %.2f\n", first.distance(second));
}
}
