Skip to content
QuizMaker logoQuizMaker
Activity
Java Programming: From Zero to Enterprise
2. Object-Oriented Programming
1. Getting Started with Java & the JVM
2. Data Types & Variables
3. Control Flow: Ifs & Loops
4. String Manipulation in Depth
5. Methods (Functions) Architecture
6. Arrays & The Enhanced For Loop
7. User Input via Scanner
8. Mathematical Operations & The Math Class
9. Operators in Depth
10. Block Scope & Variable Lifecycles
11. Introduction to Object-Oriented Programming
12. Classes & Instances Deep Dive
13. Constructors
14. Encapsulation & The 'this' Keyword
15. Inheritance: Extending Functionality
16. Polymorphism & Method Overriding
17. Abstraction & Abstract Classes
18. Interfaces: The Ultimate Contract
19. Packages & Access Modifiers
20. Enums (Enumerations)
21. Exceptions: Handling Runtime Errors
22. The 'throw' and 'throws' keywords
23. Dates, Times, and Formatting
24. Enumerable Data Structures
25. LinkedLists: The Alternative
26. HashMaps: Key-Value Architecture
27. HashSets: The Art of Uniqueness
28. Iterator: Safe Collection Traversal
29. Wrapper Classes & Autoboxing
30. Basic File I/O
31. Generics: Type-Safe Templates
32. Lambda Expressions & Functional Interfaces
33. The Stream API: Functional Data Pipelines
34. Optional: Beating the NullPointerException
35. Multithreading & Concurrency Basics
36. JDBC: Connecting to SQL Databases
37. Annotations & Reflection
38. The JVM Garbage Collector
39. Introduction to Spring Boot
40. Unit Testing with JUnit
41. Java Collections for DSA
CONTENTS

15. Inheritance: Extending Functionality

The second pillar of OOP. How to share code between parent and child classes.

Java Programming: From Zero to Enterprise
2. Object-Oriented Programming
February 22, 2026
64
A

[!NOTE] The second pillar of Object-Oriented Programming is Inheritance. It allows a new class to drastically cut down on duplicate code by inheriting all the attributes and methods of an existing class.

The 'extends' Keyword

Imagine you are building a Zoo application. You need a Lion class, a Penguin class, and a Monkey class. All of them need health, age, and a eat() method. Writing those three variables in every single class is a violation of the DRY (Don't Repeat Yourself) principle.

Instead, we create a generic Parent class (Superclass), and have the Children classes (Subclasses) inherit from it using the extends keyword.

// 1. The Superclass
public class Animal {
    protected int health = 100; // 'protected' means children can see this, but the public cannot.
    
    public void eat() {
        System.out.println("The animal consumes food.");
    }
}

// 2. The Subclass
// A Lion *is an* Animal. It gets everything Animal has automatically!
public class Lion extends Animal {
    // Unique to the Lion!
    public void roar() {
        System.out.println("ROAARRR!");
    }
}

public class Main {
    public static void main(String[] args) {
        Lion simba = new Lion();
        simba.eat(); // Inherited from Animal! Output: "The animal consumes food."
        simba.roar(); // Specific to Lion.
        System.out.println(simba.health); // Output: 100
    }
}

The 'super' Keyword

What if the Parent Class has a Constructor that requires parameters? The Child class must successfully build the Parent portion of itself before it can exist.

To achieve this, the first line of a child's constructor must use the super() keyword to pass data up to the parent.

public class Employee {
    String name;
    
    // Parent Constructor requires a Name
    public Employee(String name) {
        this.name = name;
    }
}

public class Manager extends Employee {
    int teamSize;
    
    public Manager(String name, int teamSize) {
        // 1. Call the Parent Constructor and pass the required name
        super(name); 
        
        // 2. Initialize the child's specific fields
        this.teamSize = teamSize;
    }
}

[!CAUTION] Single Inheritance Only: A Child class can only have one direct Superclass in Java. You can say class Lion extends Animal, but you CANNOT say class Lion extends Animal, Predator. This restriction prevents catastrophic ambiguity (the "Diamond Problem") common in C++.

Use Inheritance for True Is-A Relationships

Inheritance works best when the child really is a specialized version of the parent. A Manager is an Employee. A Car is a Vehicle. But a Report is not a Printer; it may simply use a printer.

Inheritance vs Composition

// Inheritance: ElectricCar is a Vehicle
class ElectricCar extends Vehicle {
}

// Composition: Order has a PaymentService
class OrderService {
    private PaymentService paymentService;
}

Use composition when a class needs help from another object. Use inheritance when the child should be usable wherever the parent is expected.

Overriding Parent Behavior

class Employee {
    double calculateBonus() {
        return 1000;
    }
}

class Manager extends Employee {
    @Override
    double calculateBonus() {
        return 3000;
    }
}

Common Mistakes

  • Using inheritance only to reuse code when composition would be clearer.
  • Making parent fields protected too quickly instead of using methods.
  • Forgetting that Java classes support only one direct parent class.
  • Creating very deep inheritance chains that are hard to reason about.

Mini Practice

Create an Employee class and two child classes: Developer and Designer. Give each child a different implementation of getRoleDescription().

Practice Lab: Employee Hierarchy

Use inheritance only where the relationship is truly is-a.

  1. Create a parent class Employee with name and base salary.
  2. Add a method calculateMonthlyPay().
  3. Create Developer and Manager child classes.
  4. Override pay calculation or role description where needed.
  5. Use super to initialize parent fields.

Goal: Practice inheritance, extends, super, and child-specific behavior.

Revision Checkpoint

  • extends: Creates a parent-child class relationship.
  • Is-a test: Use inheritance when the child truly is a parent type.
  • super(...): Calls the parent constructor.
  • Single inheritance: A class can extend only one direct parent class.
  • Composition: Prefer has-a relationships when a class only uses another object.

Before the quiz: Decide whether each relationship is inheritance or composition.

Share this article

Share on TwitterShare on LinkedInShare on FacebookShare on WhatsAppShare on Email

Test your knowledge

Take a quick quiz based on this chapter.

mediumJava
Quiz: Inheritance
10 questions5 min
Lesson 5 of 10 in 2. Object-Oriented Programming
Previous in 2. Object-Oriented Programming
14. Encapsulation & The 'this' Keyword
Next in 2. Object-Oriented Programming
16. Polymorphism & Method Overriding
Back to Java Programming: From Zero to Enterprise
Back to moduleCategories