Understanding Inheritance
Learn how inheritance in Java lets you create class hierarchies to reuse code and reduce redundancy. Understand the role of the extends keyword, protected access modifier, and super keyword for constructors. This lesson helps you grasp how subclasses inherit from superclasses, override methods, and build flexible, logical application designs.
When building complex applications, we often find ourselves writing the same code for different classes. If we are building a payroll system, we might define a Manager class and a Developer class. Both need names, IDs, and salaries. Copying and pasting this logic leads to errors and makes updates difficult. If we need to change how salaries are stored, we have to update it in multiple places.
Java solves this with inheritance, a mechanism that allows a new class to adopt the properties and behaviors of an existing class. This creates a logical hierarchy, reduces redundancy, and enables us to write cleaner, more maintainable code.
What is inheritance?
Inheritance is the mechanism by which a subclass inherits members from a superclass. The subclass contains the superclass part of the object, but access to inherited members is still controlled by access modifiers. This allows us to define a general class with common features and create specific classes that extend it.
We use specific terminology to describe this relationship:
Superclass (parent): The class being extended. It holds the common attributes and behaviors.
Subclass (child): The class that extends the superclass. It inherits features from the parent and can add its own specific features.
Inheritance models an “is-a” relationship. If we have a class Vehicle and a subclass Car, we can say “A Car is a Vehicle.” If this sentence makes logical sense, inheritance is likely the right design choice.
The protected modifier
Before we write code to extend classes, we must introduce a new access modifier: protected. ...