Java
Module 8: Inheritance & CompositionBeginner24 min read

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.

Key Takeaways & Core Concepts
  • Single: B extends A
  • Multilevel: C extends B extends A
  • Hierarchical: B extends A and C 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.

Inheritance, `super` & Method Overriding
1class Employee {
2 String name;
3 Employee(String name) { this.name = name; }
4 double bonus() { return 5000; }
5}
6
7class SeniorEngineer extends Employee {
8 SeniorEngineer(String name) { super(name); }
9 @Override
10 double bonus() { return super.bonus() + 10000; }
11}
12
13public class Main {
14 public static void main(String[] args) {
15 SeniorEngineer eng = new SeniorEngineer("Kavya");
16 System.out.println(eng.name + " Bonus: " + eng.bonus());
17 }
18}
Click code or "Edit Code" to edit
Interactive Code Block•Tab = 4 spaces•Ctrl + Enter = Run
18 lines
Note: `super.bonus()` reuses the base bonus calculation and adds the senior allowance.

Types of Inheritance in Java

  • Single: B extends A
  • Multilevel: C extends B extends A
  • Hierarchical: B extends A and C 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.

Practice & AssessmentJava Programming Tutorial

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)