Inheritance

All living things "inherit" things from their parents when they are born. For example, I inherited brown hair from my father and brown eyes from my father. My sister inherited her sneeze from my grandfather (it's uncanny).

Objects can inherit things from other classes. In fact, you have already been coding this. Whenever you use the code "implements" or "extends" you are using inheritance. Inheritance allows one class to use the methods and attributes in another class as if they where its own.

There are two major kinds of inheritance:

(a) Subclassing - extends - you are extending an existing class

(b) Subtyping - implements - you are implementing an interface

Here is an example to illustrate the difference.

Extends

In this example, there are three existing classes: zebra, horse and donkey.

Each of these classes have attributes and methods.

Decended from the zebra and the horse is a zorse, from a zebra and a donkey is a zebrass, from a horse and donkey is a mule.

A mule, for example, "extends" a horse and a donkey. It is a blend of both species.

In case you are interested, zebroids (zorse and zebrass) and mules are sterile. You need to have the two breeding species to breed one.

Implements

When you implement code, you are taking a "pattern" and making it into a full blown useful object.

For example, a equine does not exist in and of itself. It is a general classification.

The zebra, horse and donkey classes implement the equine interface and give it real characteristics.

Extends vs. Implements in Java

To this point, we have learned to "extend" some things, for example, Applets and to "implement" others, for example, ActionListeners. Why do we extend some things and implement others?

A class can implement many things. It can only extend one thing.

When you implement, you are implementing an "interface". An interface isn't actual code. It is merely a list of methods that need to appear in classes that implement that interface. For example, the ActionListener interface specifies that the public void actionPerformed (ActionEvent e) method MUST appear in any classes that implement it. You get an error if you don't have an actionPerformed method when you have implemented ActionListener.