Show Lecture.InheritanceVsComposition as a slide show.
CS253 Inheritance Vs Composition
Is-a vs. Has-a
It’s all about
Inheritance (Is-a)
vs.
Composition (Has-a)
Is-a
- Is-a is about what you are.
- A dog is a mammal.
- A real number is a scalar.
- The U.S. president is a natural born citizen.
- The U.S. president is a person born before
1990.
- A car is a vehicle.
- Beyoncé is a human being.
- Beyoncé is a singer.
- Beyoncé is a Grammy winner.
- Beyoncé is an air-breather.
- Beyoncé is a vertebrate.
- Beyoncé is a taxpayer.
Has-a
- Has-a is about what you have.
- A car has a drive shaft.
- A car has has a set of four tires.
- The Secretary of State has an administrative staff.
- A complex number has a real part.
- A complex number has an imaginary part.
- My wife has a laptop.
- My wife has a winter coat.
- My wife has a degree in nursing.
- My wife has a degree in horticulture.
- My wife has a middle name.
- My wife has a husband.
- My wife has a social security number.
- My wife has a sweet smile.
O-O relevance
In object-oriented (o-o) programming:
- Is-a refers to class inheritance (superclass/subclass,
base/derived classes).
- Has-a refers to composition (member variables).
Example
class Base {
public:
int beta;
};
class Derived : public Base {
public:
int gamma;
};
Derived
is-a Base
.
Base
has-a beta
.
Derived
has-a gamma
.
Derived
has-a beta
.
Is-a is transitive
class Mammal { };
class Feline : public Mammal { };
class Housecat : public Feline { };
Feline
is-a Mammal
.
Housecat
is-a Feline
.
Housecat
is-a Mammal
.
Another Example
class RapSheet {
...
};
class Inmate {
private:
string name;
unsigned long number;
RapSheet offenses;
};
Of course, is-a is restricted to class objects, whereas has-a
can apply to objects or built-in types.
Inmate
has-a name
Inmate
has-a number
Inmate
has-a RapSheet