Understanding Object-Oriented Design Principles

object-orientedobject-oriented-design

Suppose you have the following:

     +--------+     +------+
     | Animal |     | Food |
     +-+------+     +----+-+
       ^                 ^
       |                 |
       |                 |
  +------+              +-------+
  | Deer |              | Grass |
  +------+              +-------+

Deer inherits from Animal, and Grass inherits from Food.

So far so good. Animal objects can eat Food objects.

Now lets mix it up a bit. Lets add a Lion which inherits from Animal.

     +--------+     +------+
     | Animal |     | Food |
     +-+-----++     +----+-+
       ^     ^           ^
       |     |           |
       |     |           |
  +------+ +------+     +-------+
  | Deer | | Lion |     | Grass |
  +------+ +------+     +-------+

Now we have have a problem because Lion can eat both Deer and Grass, but Deer is not Food it is Animal.

With out using multiple inheritance, and using object oriented design, how do you solve this problem?

FYI: I used http://www.asciiflow.com to create the ASCII diagrams.

Best Answer

IS A relationships = Inheritance

Lion is an animal

HAS A relationships = Composition

Car has a wheel

CAN DO relationships = Interfaces

ICanEat

Related Topic