0% found this document useful (0 votes)
6 views2 pages

Program 04

Java program

Uploaded by

nimranazia18
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views2 pages

Program 04

Java program

Uploaded by

nimranazia18
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 2

/*

Program 04 : 2D Point Class

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.

*/

public class Mypoint {


private int x;
private int y;

Mypoint() {
this.x = 0;
this.y = 0;
}

Mypoint(int x, int y) {
this.x = x;
this.y = y;
}

void setXY(int x, int y) {


this.x = x;
this.y = y;

int[] getXY() {
int[] coordinates = {x, y};
return coordinates;
}

public String toString() {


return "(" + x + "," + y + ")";
}

double Distance(int x, int y) {


double diffx = this.x - x;
double diffy = this.y - y;

return (Math.sqrt(diffx * diffx + diffy * diffy));


}

double Distance(Mypoint another) {


return Distance(another.x, another.y);
}

double Distance() {
return Distance(0, 0);
}
}

/* create a file and store this class program in it*/

public class TestMypoint {


public static void main(String[] arg) {
Mypoint point1 = new Mypoint();
Mypoint point2 = new Mypoint(1, 2);
point1.setXY(3, 4);
System.out.println("point1:" + point1.toString());
System.out.println("point2:" + point2.getXY()[0] + "," + point2.getXY()[1]);
System.out.println("Distance b/w point1 and poin2 is" + point1.Distance(point2));
System.out.println("Distance b/w point1 and origin(0,0)" + point1.Distance());
}

You might also like