Robotics C++ Physics II AP Physics B Electronics Java Astronomy Other Courses Summer Session  

Inheritance and Composition

Inheritance

Composition

Composition Example

 

 

 

   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.

 

 

Inheritance

 

 

class Fruit

{

    //...
}

class Apple extends 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.

 

Composition

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.