The is-a relationship

Before moving forward, it is very important to understand how to find a relationship between different classes. How do we know that a student can be inherited from Person or that Circle can be inherited from the Shape class? If the designed hierarchy is correct, the child class must be a type of the parent class and both classes must have an is-a relationship between them. Take a look at the following examples:

  • Student is a person
  • Circle is a shape
  • Football player is a basketball player
  • German shepherd is a dog
  • Sofa is a bedroom

Most of these examples are correct but a few of them are completely false. Student is a person is correct because students have all the attributes and behaviors that a person has. Students also have some unique features as well. Circle is a shape is also correct, because every shape has a size and a color, so circle can be inherited from shape. Sofa is a bedroom does not make any sense, however, nor does Football player is a basketball player, because both games are completely different.

If the inheritance and the classes are well designed, every inherited class is a type of its parent class. If class B is inherited from A, then B is a type of A. As a circle is inherited from the Shape class, a circle is a type of shape. If class C is inherited from B and B is inherited from A, then C contains all features that both A and B have. A cylinder is inherited from a circle and a circle is inherited from a shape. A cylinder is therefore a type of shape as well as a circle.

An important thing to remember is that inheritance always works in one direction. A student is inherited from the Person class, which means that every student is a person. This is one-directional relationship; it won't work the other way around, because every person is not a student. Similarly, all dogs are animals, but not all animals are dogs. For this reason, a dog can be inherited from the animal class, but an animal cannot be extended from the dog class.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.117.187.62