Inheritance I
- Contents
- What is Inheritance?
- The “is a” Relationship
- Inheritance, Fields, and Methods
- Inheritance and Constructors
- Overriding Superclass Methods
- Preventing a Method from Being Overridden
- Protected Members
- Default Members
- Access Specifiers
- Chain of Inheritance
What is Inheritance?
Generalization vs. Specialization
Real-life objects are typically specialized versions of other more general objects.
For example, the term “insect” describes a very general type of creature with numerous characteristics.
Grasshoppers and bumblebees are insects.
They share the general characteristics of insects
They have special characteristics of their own.
- Grasshoppers have a jumping ability.
- Bumblebees have a stinger.
Grasshoppers and bumblebees are specialized versions of insects.
Another Example depicted as a diagram:
The “is a” Relationship
The relationship between a superclass and an inherited class is called an “is a” relationship.
- A grasshopper “is a” insect.
- A square “is a” rectangle.
- A square “is a” quadrilateral.
- A square “is a” shape.
A specialized object has:
- all of the characteristics of the general object
- plus additional characteristics that make it special
In object-oriented programming, inheritance is used to create an “is a” relationship among classes.
We can extend the capabilities of a class.
Inheritance involves a superclass and a subclass.
- The superclass is the general class.
- The subclass is the specialized class.
The subclass is based on, or extended from, the superclass.
- Superclasses are also called base classes.
- Subclasses are also called derived classes.
The relationship of classes can be thought of as parent classes and child classes.
The subclass inherits fields and methods from the superclass without any of them being rewritten.
New fields and methods may be added to the subclass.
The Java keyword
extends
is used on the class header to define the subclass.