A class called MyPoint, which models a 2D point with x and y coordinates, is designed as
follows:
● Two instance variables x (int) and y (int).
● A default (or "no-arg") constructor that construct a point at the default location of (0, 0).
● A overloaded constructor that constructs a point with the given x and y coordinates.
● A method setXY() to set both x and y.
● A method getXY() which returns the x and y in a 2-element int array.
● A toString() method that returns a string description of the instance in the format "(x, y)".
● A method called distance(int x, int y) that returns the distance from this point to another
point at the given (x, y) coordinates
● An overloaded distance(MyPoint another) that returns the distance from this point to the
given MyPoint instance (called another)
● Another overloaded distance() method that returns the distance from this point to the origin
(0,0) Develop the code for the class MyPoint. Also develop a JAVA program (called
TestMyPoint) to test all the methods defined in the class.
package test;
public class MyPoint
{
private int x;
private int y;
// Default constructor
public MyPoint()
{
this.x = 0;
this.y = 0;
}
// Overloaded constructor
public MyPoint(int x, int y)
{
this.x = x;
this.y = y;
}
// Method to set both x and y
public void setXY(int x, int y)
{
this.x = x;
this.y = y;
}
// Method to get x and y in a 2-element int array
public int[] getXY()
{
return new int[]{x, y};
}
// toString method to return a string description of the instance
@Override
public String toString()
{
return "(" + x + ", " + y + ")";
}
// Method to calculate distance from this point to another point
public double distance(int x, int y)
{
int xDiff = this.x - x;
int yDiff = this.y - y;
return Math.sqrt(xDiff * xDiff + yDiff * yDiff);
}
// Overloaded distance method to calculate distance from this point to another MyPoint
instance
public double distance(MyPoint another)
{
return distance(another.x, another.y);
}
// Overloaded distance method to calculate distance from this point to the origin (0,0)
public double distance()
{
return distance(0, 0);
}
public static void main(String[] args)
{
// Creating MyPoint objects
MyPoint point1 = new MyPoint();
MyPoint point2 = new MyPoint(3, 4);
// Testing setXY and getXY methods
point1.setXY(1, 2);
int[] coordinates = point1.getXY();
System.out.println("Point1 coordinates: (" + coordinates[0] + ", " + coordinates[1] +
")");
// Testing toString method
System.out.println("Point2 coordinates: " + point2);
// Testing distance methods
System.out.println("Distance from Point1 to (5, 6): " + point1.distance(5, 6));
System.out.println("Distance from Point2 to Point1: " + point2.distance(point1));
System.out.println("Distance from Point1 to the origin: " + point1.distance());
}
}