Java Inheritance, extends, super & Composition
Reuse and specialize classes using single, multilevel, and hierarchical inheritance, invoke parent constructors with super(), and prefer composition when appropriate.
- Single:
B extends A - Multilevel:
C extends B extends A - Hierarchical:
B extends AandC extends A - Multiple Inheritance: Disallowed for classes (prevents the Diamond Problem, where two parent classes define conflicting implementations of the same method), but supported for interfaces (
class X implements A, B).
Introduction
Inheritance models an IS-A relationship (SeniorEngineer IS-A Employee) using extends. The subclass inherits all public and protected members of its superclass and can add new fields/methods or override existing behavior.
Types of Inheritance in Java
- Single:
B extends A - Multilevel:
C extends B extends A - Hierarchical:
B extends AandC extends A - Multiple Inheritance: Disallowed for classes (prevents the Diamond Problem, where two parent classes define conflicting implementations of the same method), but supported for interfaces (
class X implements A, B).
Constructor Chaining with super()
Every subclass constructor implicitly calls super() on line 1 unless you explicitly call super(args) or this(args). If the parent class lacks a no-arg constructor, you must call super(args) explicitly.
Composition vs Inheritance (HAS-A vs IS-A)
Favor Composition (Order HAS-A PaymentProcessor) over deep inheritance hierarchies when you only want code reuse without tight coupling—composition lets you swap behavior at runtime and avoids breaking subclasses when parent internals change.
Test Your Understanding
Reinforce core concepts with interactive multiple-choice questions, live coding challenges, and top technical interview questions.
Your Current Score
0 / 0 correct(0 attempted)