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
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) {. . .}
}
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;
}
Advantages of inheritance over composition:
even wit the right mechanisms, software reuse not guaranteed to occur
Also need the right culture