首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >类型边界: Apple和Orange

类型边界: Apple和Orange
EN

Stack Overflow用户
提问于 2020-12-08 18:39:11
回答 3查看 72关注 0票数 0
代码语言:javascript
复制
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);
    }
}

任务是重新设计类型系统,并实现水果之间的正确比较(苹果和苹果,橙子和橙子,但不是苹果和橙子,以及橙子和苹果)。

和“苹果与橙子和橙子与苹果的比较应该在编译时受到限制”。

不知道如何正确更改,请给个提示。

EN

回答 3

Stack Overflow用户

发布于 2020-12-08 18:49:24

我建议在Fruit中引入一个泛型,它代表"SELF type..“

代码语言:javascript
复制
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);
            }
        }
    }

证明:

票数 0
EN

Stack Overflow用户

发布于 2020-12-08 19:04:06

代码语言:javascript
复制
class Fruit {

private final int weigth;

public Fruit(int weight) {
    this.weigth = weight;
}


public int getWeigth() {
    return this.weigth;
}

}

代码语言:javascript
复制
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());
}

}

代码语言:javascript
复制
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());
}

}

票数 0
EN

Stack Overflow用户

发布于 2020-12-09 16:52:11

如果两个结果不能比较,那么为什么要实现可比性呢?应该在具体的类级别定义可比较对象,这样就可以解决您的问题。

或者,如果你想在现有的类中放入check,你可以这样做

代码语言:javascript
复制
@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");
}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/65197346

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档