Inheritance

Inheritance

The Is A relationship between two classes shows that one class is a subset of the other class. One class is further defined or extended by another class, this class being a more specific case. Classes already defined in the Java packages/libraries can be extended, as well as the classes that we develop.

Superclass - The class which is being extended is referred to as the superclass, base class or parent class. Each superclass can have any number of subclasses, each parent can have 1 child class, 2, 3, 4, ... etc.

Subclass - The class which implements the extension is referred to as the subclass or child class. Each subclass can only have one superclass, each child can only have ONE parent. Java does not allow Multiple Inheritance, in other words a subclass can not have multiple superclasses. A subclass inherits all of the non-private attributes and methods of the superclass (also those of the superclasses superclass, the grandparent, and so on).

All classes have a default superclass, the java.lang.Object class. This does not have to be specified, instead when a program is compiled it is assumed to be the superclass if one is not listed. The java.lang.Object class is referred to as the root of all classes.

Extends Keyword - The keyword extends is used to create the inheritance relationship. First the class being created is listed as usual (subclass), then extends, then the class being extended (superclass). Here is the format, the keywords are in bold:
class subclass extends superclass {
  // ...
}
Protected - In addition to being declared public or private, a variable or method can be declared to be protected. A protected variable or method can only be seen or accessed from the current class or from within a subclass.

Example Class Hierarchy

Shapes with Inheritance