请自定义一个接口 MyComparable来比较对象大小。 请定义接口,并让Point具备比较的能力,我们假设按照与原点的距离进行比较。 MyComparable 方法 compareTo(Object other):抽象方法,比较对象大小,方法的参数是一个Object 类型的变量 other,表示与另一个参与比较的对象。 Point 属性 x:点的坐标x。 y:点的坐标y。 构造方法 Point(int x,int y):初始化两个属性。 方法 compareTo(Object other):比较对象与
时间: 2023-11-27 13:54:01 浏览: 35
原点的距离,返回值为int类型,如果当前对象的距离大于other对象的距离,返回正整数;如果当前对象的距离小于other对象的距离,返回负整数;如果两者距离相等,返回0。
代码如下:
```java
public interface MyComparable {
int compareTo(Object other);
}
public class Point implements MyComparable {
private int x;
private int y;
public Point(int x, int y) {
this.x = x;
this.y = y;
}
public int getX() {
return x;
}
public int getY() {
return y;
}
@Override
public int compareTo(Object other) {
if (!(other instanceof Point)) {
throw new IllegalArgumentException("Object is not an instance of Point");
}
Point point = (Point) other;
double distance1 = Math.sqrt(Math.pow(this.x, 2) + Math.pow(this.y, 2));
double distance2 = Math.sqrt(Math.pow(point.getX(), 2) + Math.pow(point.getY(), 2));
if (distance1 > distance2) {
return 1;
} else if (distance1 < distance2) {
return -1;
} else {
return 0;
}
}
}
```
这样,我们就定义了一个可以比较Point对象大小的接口MyComparable,并让Point类实现了该接口。在compareTo方法中,我们通过计算当前对象与原点的距离和另一个对象与原点的距离,来比较两个对象的大小。