Inheritance and Composition
One of the fundamental activities of any software system design is
establishing relationships between classes.
Two fundamental ways to relate classes are inheritance and
composition.
|
class Fruit { { |
![]() |
In this simple example, class Apple is related to class Fruit by
inheritance, because Apple extends Fruit.
In this example, Fruit is the superclass and Apple is the
subclass.
|
By composition, we simply mean creating an object of another class in the current class class Fruit {
//...
}
class Apple
{
private Fruit fruit = new Fruit();
//...
}
|
![]() |
In the example above, class Apple is related to class Fruit by composition,
because Apple has a variable that holds a reference to a Fruit object.
In this example, Apple is what we cakk the front-end class
and Fruit is called the back-end class.
In a composition relationship, the front-end class holds a reference
in one of its instance variables to a back-end class.