在這種情況下,反身意味着obj.compareTo(obj) == 0
。這裏反思意味着什麼?
就compareTo(T o)指定的契約而言,如果涉及的類不能進行有意義的比較,那麼所需的語義將引發ClassCastException。
例如鑑於
class Fruit {/* ..*/ }
class Apple extends Fruit {/* .. */ }
@Ignore("bad OO")
class GrannySmithApple extends Apple {/* .. */ }
class Orange extends Fruit {/* ... */ }
人們可以說,
Fruit a = new Apple();
Fruit b = new GrannyApple();
Fruit c = new Orange();
// compare apples with apple?
// makes sense to expect an int value
r = a.compareTo(b)
// compare apples with oranges?
// makes sense to expect an exception
boolean excepted = false;
try {
c.compareTo(a);
} catch (ClassCastException e) {
excepted = true;
} finally {
assert excepted : "How can we compare apples with oranges?"
}
假設它是一個抽象類或接口,你爲什麼不只是讓'BaseClass'實現或擴展'Comparable'並利用實施細節班級的實施者? – BalusC
你是否暗示BaseClass實現了compareTo(BaseClass),然後讓SubClass覆蓋它? – fishtoprecords