Introduction to Inheritance
Explore the concept of inheritance in Java programming by understanding how classes relate through superclasses and subclasses. Learn to recognize hierarchical structures and the 'is-a' relationship, which are foundational for building efficient code and designing programs such as banking applications.
We'll cover the following...
Introduction
When a baby is born, it inherits its parents’ genes and acquires physical attributes from both the mother and father. As the baby grows, it forms its own personality.
Similarly, technological products inherit features from their predecessors for backwards compatibility. For example, the Intel Pentium processor inherited many of the features defined by the Intel 486 processor, which inherited features from earlier processors.
Have you ever looked at a family tree? It is a chart representing family relationships using a conventional tree structure. It is often presented with the oldest generations at the top and the newer generations at the bottom.
Concept of hierarchy
The relationships are shown via a hierarchy, and you can clearly see the relationship between the two individuals. Consider this example:
This is another example of a hierarchy:
- Triangle and quadrilateral both are shapes.
- A right-angle triangle is a triangle, which is a shape.
- An isosceles triangle is a triangle, which is a shape.
- A square is a quadrilateral, which is a shape.
- A rectangle is a quadrilateral, which is a shape.
The diagram goes from general (top) to specific (bottom), with each item in the hierarchy inheriting the properties and behaviors of the item above it.
In general, inheritance is used to implement an “is-a” relationship. For example, a square is a quadrilateral, and a quadrilateral is a shape.