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);
}
}任务是重新设计类型系统,并实现水果之间的正确比较(苹果和苹果,橙子和橙子,但不是苹果和橙子,以及橙子和苹果)。
和“苹果与橙子和橙子与苹果的比较应该在编译时受到限制”。
不知道如何正确更改,请给个提示。
发布于 2020-12-08 18:49:24
我建议在Fruit中引入一个泛型,它代表"SELF type..“
class Fruit<S extends Fruit> implements Comparable<S> {
private final int weigth;
public Fruit(int weight) {
this.weigth = weight;
}
@Override
public int compareTo(S other) {
return Integer.compare(this.weigth, other.getWeigth());
}
public int getWeigth() {
return this.weigth;
}
}
class Apple extends Fruit<Apple> {
public Apple(int weight) {
super(weight);
}
}
class Orange extends Fruit<Orange> {
public Orange(int weight) {
super(weight);
}
}
}证明:

发布于 2020-12-08 19:04:06
class Fruit {
private final int weigth;
public Fruit(int weight) {
this.weigth = weight;
}
public int getWeigth() {
return this.weigth;
}}
class Apple extends Fruit implements Comparable<Apple> {
public Apple(int weight) {
super(weight);
}
@Override
public int compareTo(Apple o){
return Integer.compare(this.getWeigth(), o.getWeigth());
}}
class Orange extends Fruit implements Comparable<Orange>{
public Orange(int weight) {
super(weight);
}
@Override
public int compareTo(Orange o){
return Integer.compare(this.getWeigth(), o.getWeigth());
}}
发布于 2020-12-09 16:52:11
如果两个结果不能比较,那么为什么要实现可比性呢?应该在具体的类级别定义可比较对象,这样就可以解决您的问题。
或者,如果你想在现有的类中放入check,你可以这样做
@Override
public int compareTo(Fruit other) {
if(other.getClass().equals(this.getClass())){
return Integer.compare(this.weigth, other.weigth);
}
throw new NotComparableException("Object are of different class, and so can't be compared");
}https://stackoverflow.com/questions/65197346
复制相似问题