Creating a simple 2D point class in Java is fairly simple. A Cartesian coordinate system uses points in two dimensions along an x-axis and y-axis. Each point has a pair of x and y coordinates along these two axes.
We define a SimplePoint class that has two private properties x and y:
public class SimplePoint {
private double x,y;
}
To access each property, create two getter methods in the class:
public double getX() { return x; };
public double getY() { return y; };
We could also provide setter methods if desired.
A constructor method makes it convenient to create a SimplePoint object at a specific x,y location:
public SimplePoint(double x1, double y1) {
x = x1;
y = y1;
}
For example, to create two SimplePoint objects at x,y positions 2,1 and 8,2:
SimplePoint p1 = new SimplePoint(2,1);
SimplePoint p2 = new SimplePoint(8,2);
Finally, here is a distance() function to calculate the distance between two SimplePoint objects:
public double distance(SimplePoint p) {
return Math.sqrt( Math.pow(p.getX()-x,2) + Math.pow(p.getY()-y,2) );
}
To calculate and output the distance between p1 and p1:
System.out.println( p1.distance(p2) ); // 6.082762530298219
Here is the complete source code for the SimplePoint class, including the sample main() method:
public class SimplePoint {
private double x,y;
public SimplePoint(double x1, double y1) {
x = x1;
y = y1;
}
public double getX() { return x; };
public double getY() { return y; };
public double distance(SimplePoint p) {
return Math.sqrt( Math.pow(p.getX()-x,2) + Math.pow(p.getY()-y,2) );
}
public static void main(String[] args) {
SimplePoint p1 = new SimplePoint(2,1);
SimplePoint p2 = new SimplePoint(8,2);
System.out.println( p1.distance(p2) ); // 6.082762530298219
}
}
Java makes it easy to represent 2D points. The SimplePoint class is one way to do that. Create SimplePoint objects at specified locations, then use the distance() function to calculate the distances between them.
Thanks for reading.
Follow me on Twitter @realEdwinTorres for more programming tips. 😀
Top comments (1)
Good example
You may also, add fountion to retive, p1 in polar. It will return r, cita