Inheritance and substitutability

Idealization of inheritance: instance of subclass can substitute for instance of parent

Abstract concept captured with two rules of thumb

is-a relation
 
     "A dog  is-a mammal" sounds right
 
      Natural from dog to inherit from mammal

has-a relation

    "A car is-a(n) engine" sounds wrong

    Not natural to use inheritance

    but " a car has-a(n)engine" sounds right

    Can use composition

 
            Two approaches to software reuse in OOP

Inheritance - the is-a relationship

 Composition(aggregation)- the  has-a relationship                       Example -Building sets from Lists

Suppose already have List data type with the following behavior:

class List
  {
      public List( ) {. . . . }
      public void add(int ) {. . . . }
      public void remove(int ) {. . . . }
      public boolean includes(int ) {. . . . }
      public int firstElement( ) {. . . . }
     . . . . . .
  }

Wish to build a set data type - elements are unique and unordered in set

                        Using Inheritance

 class Set extends List
    {
         public void add(int) {. . .}
     }
 

                       Using Composition(Aggreration)

 class Set
   {
          public Set( ) {. . .data = new list( ). . . }
          public void add(int ) {. . . . }
          public void remove(int ) {. . . . }
          public boolean includes(int ) {return data.includes(int) }
          private list data;
  }

                       Comparison of Inheritance and Composition

Advantages of inheritance over composition:

Advantages of   composition over inheritance:                     Will Widespread Software Reuse Become Reality?

      even wit the right mechanisms, software reuse not guaranteed to occur

     Also need the right culture