Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In inheritance, what if subclass does not adhere to all super class behavior?

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!

like image 218
user341155 Avatar asked Dec 27 '22 00:12

user341155


2 Answers

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.

like image 55
Alberto Zaccagni Avatar answered Mar 29 '23 23:03

Alberto Zaccagni


Your assertions contradict each other.

  • 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.

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.

like image 33
Andy Thomas Avatar answered Mar 30 '23 00:03

Andy Thomas