java类型的边界:apple和orange

fdbelqdn  于 2021-06-30  发布在  Java
关注(0)|答案(3)|浏览(383)
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);
    }
}

任务是重新设计类型系统,实现水果(苹果与苹果、橙子与橙子,但不是苹果与橙子、橙子与苹果)的正确比较。
而“苹果与橘子、橘子与苹果的比较,应在编制时加以限制”。
不知道如何正确更改,请给出提示。

vql8enpb

vql8enpb1#

如果两个水果不能比较,那为什么要比较呢?comparable应该在具体的类级别上定义,这样就可以解决您的问题。
或者,如果您想在现有类中放入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");
}
pzfprimi

pzfprimi2#

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());
}

}

i2byvkas

i2byvkas3#

我建议给水果引入一个泛型,它代表“自我类型…”

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);
            }
        }
    }

证明:

相关问题