Inheritance creates a new class definition by building upon an existing definition (you
extend the original class).
The new class can, in turn, can serve as the basis for another class definition.
- All Java objects use inheritance.
- Every Java object can trace back up the inheritance tree to the generic class
extends is used to base a new class upon an existing class
Several pairs of terms are used to discuss class relationships (these are not keywords).
- Note that traditionally the arrows point from the inheriting class to
the base class, and the base class is drawn at the top - in the Unified
Modeling Language (UML)
the arrows point from a class to another class that it depends upon (and
the derived class depends upon the base class for its inherited code).
- The parent class/child class terms are not recommended, since parent and
child is more commonly used for ownership relationships (like a GUI window
is a parent to the components placed in it).
A derived class instance may be used in any place a base class instance would
work - as a variable, a return value, or parameter to a method.
Inheritance is used for a number of reasons (some of the following overlap):
- To model real-world hierarchies.
- To have a set of pluggable items with the same "look and feel," but different internal workings.
- To allow customization of a basic set of features.
- When a class has been distributed and enhancements would change the way existing methods work
(breaking existing code using the class).
- To provide a "common point of maintenance."
When extending a class, you can add new fields and methods and you can change the behavior of
existing methods (which is called overriding the methods).
- You can declare a method with the same signature and write new code for
- You can declare a field again, but this does not replace the original field; it shadows
it (the original field exists, but any use of that name in this class and its descendants
refers to the memory location of the newly declared element).