In OOP, inheritance is the mechanism which allows a code module (commonly called a class) to take on the characteristics of a parent module, redefine some and add to them. Inheritance is necessary due to the Open Closed Principle.

Public inheritance refers to the access control on the inherited features - with public inheritance, the features of the base class are available to the rest of the program to access.

Use public inheritance to implement "isa" relationships. In example (C++):


class Animal {
  public:

  void Eat();
  void Sleep();
  void Mate();
  void Defecate();
};

class Elephant : public Animal {
  public:
  
  void WashSelfWithTrunk();
};

An elephant "isa" animal, so public inheritance should be used to model the elephant. Other modules in the program can then make the elephant do all the usual animal stuff, plus the elephant stuff. If we'd used private inheritance other modules wouldn't be able to make the elephant Mate(). That's no way to live.

Be careful with "isa" relationships, as things are not always as clear as they seem. For instance, common sense tells you that a square "isa" rectangle. But as it happens, the functions used to manipulate squares (which have the same length and width) are often quite different to those used to manipulate rectangles, which have variable lengths/widths and are therefore more complex.

More

Log in or registerto write something here or to contact authors.