【发布时间】:2021-03-19 16:21:12
【问题描述】:
class Fruit implements Comparable<Fruit> {
private final int weigth;
public Fruit(int weight) {
this.weigth = weight;
}
@Override
public int compareTo(Fruit other) {
return Integer.compare(this.weigth, other.weigth);
}
public int getWeigth() {
return this.weigth;
}
}
class Apple extends Fruit {
public Apple(int weight) {
super(weight);
}
}
class Orange extends Fruit {
public Orange(int weight) {
super(weight);
}
}
任务是重新设计类型系统并实现水果之间的正确比较(苹果与苹果,橙子与橙子,但不是苹果与橙子和橙子与苹果)。
并且“Apples with Oranges 和 Oranges with Apples 的比较应该在编译时进行限制”。
不知道怎么改,请指教。
【问题讨论】:
-
Fruit无法再实现Comparable<Fruit>。 -
为什么不在基类中实现接口呢?
-
我尝试在 Apple 和 Orange 类中实现它,但系统使用 Fruit apple = ..., Fruit orange = ..., 然后是 apple.compareTo(orange);
-
“但系统使用”并不能阻止“在编译时限制苹果与橙子和橙子与苹果的比较”的含义?
-
哦,我真的很笨,对不起,我认为这意味着错误应该在 compareTo 函数的参数中。谢谢
标签: java generics comparator