Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 3
Program 04 :
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.
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; }
// Set both x and y
public void setXY(int x, int y) {
this.x = x;
this.y = y;
// Get x and y in a 2-element int array
public int[] getXY() {
return new int[]{x, y};
// Return a string description of the instance in the format "(x, y)"
public String toString() {
return "(" + x + ", " + y + ")";
// Calculate distance from this point to another point at (x, y) coordinates
public double distance(int x, int y) {
int xDiff = this.x - x;
int yDiff = this.y - y;
return Math.sqrt(xDiff * xDiff + yDiff * yDiff);
// Calculate distance from this point to another MyPoint instance (another)
public double distance(MyPoint another) {
return distance(another.x, another.y);
// Calculate distance from this point to the origin (0,0)
public double distance() {
return distance(0, 0);
public class TestMyPoint {
public static void main(String[] args) {
// Creating MyPoint objects using different constructors