OOP Fundamentals (2 of 3)

Object Oriented Programming Fundamentals

An important aspect of OOP is reuse of classes using composition and inheritance.

Composition is using objects of existing classes into a new class. It represents ‘has-a‘ relationship. e.g. car has-a engine.

composition
Composition (has-a)

Inheritance is creating new classes as type of existing classes. It represents ‘is-a‘ relationship. In Java code, after specifying the name of derived (new) class use the keyword extends followed by name of base (existing) class .

With inheritance derived class gets all the public & protected attributes and methods of base class. There are two more access specifier (other than private and public) –

  • Protected – Like private, protected  entity is accessible to only the Class which defines it. Unlike private, protected entity of base class is available in the derived class.
  • Package – This is the default access where entity is accessible within the package but is private out of package.
inheritance
Inheritance (is-a)

The derived class may add more attribute & methods to the base class. Internally derived class has a object of base class but externally it exposes an extended interface of base class. So,  derived class is a wrapper over base class with some more specific functionality.

Initialization

Since base class is wrapped inside derived class, it becomes responsibility of derived class to do initialization of base class. Java helps here by calling the constructor of base class from the constructor of derived class, but this automatic help is available only in case of default constructors.

When dealing with constructors having arguments, the derived-class constructor needs to explicitly invoke the base-class constructor using super keyword. For example:

Class Furniture {

  Furniture(int i) {

    print(“Creating Furniture”);

  }

}

Class Table extends Furniture {

  Table(int i) {

    super (i);

    print(“Creating Table”);

  }

}

In the above example, constructor Table(int) invokes super(int) which is effectively Furniture(int). A derived class constructor must initialize the base class before doing anything else because initialization of derived may depend on the base class.