logo Practice-It logo

BJP4 Exercise 10.18: ComparablePoint

Related Links:
Author: Marty Stepp (on 2016/09/08)

Suppose that a class Point2D has been defined for storing a 2-dimensional point with x and y coordinates (both as doubles). (In our section handout, the class was called Point, but we have renamed it here because Practice-It uses a class named Point for other purposes.) The class includes the following members:

NameDescription
private double x the x coordinate
private double y the y coordinate
public Point2D() constructs the point (0, 0)
public Point2D(double x, double y) constructs a point with the given coordinates
public void setLocation(double x, double y) sets the coordinates to the given values
public double getX() returns the x coordinate
public double getY() returns the y coordinate
public String toString() returns a String in standard "(x, y)" notation
public double distance(Point p) returns the distance from another point

Your task is to modify the class to be Comparable by adding an appropriate compareTo method. Points should be compared relative to their distance from the origin, with points closer to the origin considered "less" than points farther from it. The distance between two points is defined as the square root of the sum of the squares of the differences between the x and y coordinates.

Type your solution here:


This is a partial class problem. Submit code that will become part of an existing Java class as described. You do not need to write the complete class, just the portion described in the problem.

You must log in before you can solve this problem.


Log In

If you do not understand how to solve a problem or why your solution doesn't work, please contact your TA or instructor.
If something seems wrong with the site (errors, slow performance, incorrect problems/tests, etc.), please

Is there a problem? Contact a site administrator.