null
生きている動物の死亡日に戻ることは完全に合理的ですが、このような場合、ブール値の死亡チェックを提供する方が良いと思います:
public boolean isDead() {
return deathDate != null;
}
これにより、属性の不器用な null チェックを行わずに、インスタンスの死をチェックする合理的な方法が提供されます。
// this is ugly and exposes the choice of the value of the field when alive
if (animal.getDeathDate() != null) {
// the animal is dead
}
メソッドが整っていれば、これisDead()
を行う権利があります。
public Date getDeathDate() {
if (deathDate == null)
throw new IllegalStateException("Death has not occurred");
return deathDate;
}
カメの飛行速度に関しては、同じアプローチを適用できますが、クラスの設計に問題があると私は主張します.すべての動物が飛ぶわけではないので、Animal
クラスにはメソッドがありませんgetFlyingSpeed()
.
代わりに、次のようなものを使用します。
interface Flyer {
Integer getFlightSpeed();
}
class Animal {}
class Turtle extends Animal {}
class Eagle extends Animal implements Flyer {
public Integer getFlightSpeed() {
//
}
}