Like there is Mammal class have behavior of walking which all subclasses should adhere to.
But there are few mammals like Dolphin and Bat which does not have this behavior possessed.
How can we implement this?
As per me, all subclasses should adhere to all behavior related to super class.
Any help is appreciated. Thanks!
The Mammal class should only define common characteristics to all mammals, as you said walking is not a common feature.
Behaviour could be added by using interfaces, like in the following example
class abstract Mammal {
abstract void regulateTemperature();
}
interface CanFly {
void land();
void takeOff();
}
class Bat extends Mammal implements CanFly {
}
Sorry if I've made syntax errors, my Java is a bit rusty, but you got the idea, just be as generic as you can in your base class. That said I agree with @dystroy, it's way too difficult to get inheritance right with the animal domain. You might want to try by modelling a lamp, or a shirt, start with something way more simple than this.
Your assertions contradict each other.
Either all subclasses have the behavior, or not all have the behavior. You can't have both.
In object-oriented design, it is useful for all subclasses to support the contracts of their superclass, so that an instance of any subclass can be used anywhere that a superclass is referenced. This is known as the Liskov substitution principle.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With