Inheritance

The Open-Closed Principle states:

Systems should be open to extension, but closed to modification.

At first this sounds like a contradiction. How can we extend a system without modifying it? At the level of individual classes, this is accomplished by declaring that a class extends another class. The extending class (called the specialization or subclass) inherits all of the members (methods and fields) from the extended class (called the generalization or super class).

The specialization can add additional members or override inherited members.

Inheritance is transitive. If A extends B and B extends C, then A inherits all of the members of B and C.

In Java all classes implicitly (without declaration) inherit from the Object class.

Example

A program consists of many commands. Currently, there are four types of commands:

Here's an implementation: Program.java

Notes

·       It's easy to add new types of commands without modifying any of the classes above. For example, how could we add an exponentiation command?

·       The four extending classes: AddCommand, etc. inherit the arg1 and arg2 fields from extended Command class. For convenience, we have declared these fields to be protected, which means they can be accessed in the extensions.

·       The extending classes also inherit the execute method from Command. Unfortunately, this method is abstract (note italics). Which means the extending classes inherit an obligation to implement this method. It also means that Command class is abstract (can't be instantiated).

·       Thanks to polymorphism, any type of command could appear in a program's list of commands.

·       Because of the abstract execute method, the program's execute method is confident that no matter what types of notes it encounters, all will have an execute method.

·       Notice how the AddCommand constructor calls the Command constructor.