簡體   English   中英

類型界限:Apple 和 Orange

[英]Type Bounds: Apple and Orange

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

任務是重新設計類型系統並實現水果之間的正確比較(蘋果和蘋果,橙子和橙子,但不是蘋果和橙子,橙子和蘋果)。

並且“應在編譯時限制蘋果與橙子和橙子與蘋果的比較”。

不知道怎么改,請指教。

我建議向 Fruit 引入一個表示“SELF 類型..”的泛型

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

證明: 截屏

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

}

如果兩個水果不能比較,那為什么要實現 Comparable 呢? Comparable 應該在具體的 class 級別定義,這樣它將解決您的問題。

或者,如果您想檢查現有的 class,您可以執行類似的操作

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM