Limitations in subclasses OOP

2 min read Original article ↗

I think you should use Composition rather than inheritance in this case, or have various subclasses that make up the human.

While I do understand your logic, a BaseClass is a contract, that guarantees all classes of that type should adhere to this behavior, having a subclass that removes the parent method is a big NO NO..

While you could throw various exceptions, I wouldn't go down that path at all. Think about it this way, say I am a developer who only needs to access Human object, I expect a certain behavior, and all of a sudden I call an interface method and get..an Exception just because I called it?? You should not be aware of the derived classes implementations and when you can or cano't call them.

Here are a few solutions:

Make Human a composition of BasicHumanFunctions, VisionSystem, etc. Then blind man would have only a few of those.

class Human {
  private BasicHumanFunctions _basicFunctions; //contains breathe funcitonality.
  private VisionSystem _vision; //contains see
}

class BlindMan {
   private BasicHumanFunctions _basicFunctions;
}

Make Human base class contain only the same behaviour all humans would like breathing etc, and then create a HealthyHuman and a BlindHuman etc, each creating their own methods. You can then use HealthHuman and subclass that further if you need.

class Human {
   void breathe() {};
   // other Human basic functions;
} 

class HealthyHuman extends Human {
   void see() {};
   //other healthy human functions
}

class BlindHuman extends Human {
  void useCane() {};
}

For the second case you can still use composition too to share behaviour:

class BlindHuman extends Human {
   private VoiceSubsystem _voice = new VoiceSybsystem();
   void speaker() {  _voice.speaker();}
}