Inheritance is the pillar of Java that turns "Code Reusability" into reality. It is a mechanism where a new class (Subclass) acquires the properties and behaviors (fields and methods) of an existing class (Superclass). This allows developers to build upon existing code without reinventing the wheel.
Inheritance always operates on an IS-A relationship. For example, "A Car IS-A Vehicle" or "A Surgeon IS-A Doctor." If this logical link exists, inheritance is likely the correct design choice.
In Java, we use the extends keyword to establish this link.
Java supports several hierarchical structures, but with a specific architectural constraint regarding classes:
A subclass inherits from one single superclass. (Class B extends A)
A derived class is inherited by another class. (C extends B, and B extends A)
Multiple subclasses inherit from one single parent. (B and C both extend A)
When using inheritance, the child class often needs to interact with the parent class. The super keyword is a reference variable used to refer to immediate parent class objects.
Primary Applications of super:
super(); calls the parent constructor (must be the first line).If a subclass provides a specific implementation for a method that is already provided by its parent class, it is known as Method Overriding.
@Override annotation is highly recommended to prevent syntax errors during compilation.
The following example demonstrates how the extends and super keywords function within a real-world scenario.
When you instantiate a child class (e.g., new Car()), the JVM handles memory in a specific sequence:
| Concept | Execution Reality |
|---|---|
| Constructor Chain | The parent constructor is executed first, followed by the child's constructor. |
| Instance Variables | One single object is created in the Heap, but it contains all fields from both the parent and the child. |
Sometimes you want to restrict inheritance for security or design reasons. The final keyword is your primary tool:
String class).Q: Why does Java use 'extends' instead of 'inherits'?
A: The keyword extends implies that the subclass is adding more functionality to the parent, thus "extending" its capabilities, which is a more accurate description than simply inheriting.
Q: Can a subclass constructor be private?
A: Yes, but then that subclass cannot be instantiated from outside, and no other class can inherit from it (unless it’s an inner class).
Q: Is every class in Java inherited from something?
A: Yes! Every class in Java implicitly inherits from the Object class (java.lang.Object) if no other parent is specified.
Inheritance is not just about reducing the amount of code you write; it is about creating a logical, scalable architecture. By following the "Don't Repeat Yourself" (DRY) principle, you ensure that your Java applications are easier to maintain, debug, and expand over time.
Next: Master Java Polymorphism →