Composition or aggregation is an example of
a "has-a" relationship between classes.
Inheritance is an example of an
"is-a" relationship between classes.
Inheritance is a way to use an existing class as the base
of a new derived class. If you have a class that is debugged
and working well, and you need to add some data and/or
functionality to it, you may not want to modify it and
take the risk of adding bugs to it. Instead you create a
new class based on the old class.
We can use a Library "Inheritance Hierarchy" to represent
the various types of books in a library:
What do all Books have in common?
How are all Books treated the same?
What do some of the subclasses of the Book superclass
have that the other subclasses don't?
How are the different subclasses of Books treated
What do all Employees have in common?
How are they treated the same?
What do the different types of Employees NOT have in common?
How are they treated differently?
Single vs. Multiple Inheritance
The Library and Business Hierarchies are examples of
"single inheritance". Each subclass is derived from a
Java ONLY supports single inheritance, but it allows
classes to extend a class while implementing
one or more interfaces which is similar to
"Multiple inheritance", in which a subclass can be derived
from more than one superclass is allowed in the C++
programming language (and possibly others). It is quite
complicated and can introduce ambiguity and performance
problems which is why Java does not allow it!
A mini-van is a "real-life" example of multiple inheritance: