Skip to main content

Inheritance in Java with example

Mastering Inheritance in Java: Core Concepts, Code Examples, and Best Practices

Object-oriented programming (OOP) relies heavily on code reuse, hierarchical modeling, and architectural extensibility. In Java, inheritance is the foundational mechanism that allows a new class to adopt the fields, methods, and behaviors of an existing class. Understanding how inheritance works at bytecode and runtime levels is essential for writing clean, maintainable, and scalable enterprise applications—whether you are building standalone utilities or modern Dockerizing a Spring Boot Application with MySQL architectures.

Pick a language, then press Listen.

This comprehensive guide breaks down the mechanics of Java inheritance, constructor chaining, the use of the super keyword, method overriding, and why Java restricts certain inheritance structures.

1. The Problem Statement: Why Inheritance Exists

Java Inheritance Architecture Flow Java Inheritance Architecture Flow 1 Identify Common Attributes Locate shared fields and methods across multiple entity classes. 2 Define Superclass Create a parent class housing the generalized state and behavior. 3 Implement Subclass Use the extends keyword to inherit non-private superclass members. 4 Invoke Constructor Chaining Utilize the super keyword to initialize parent state securely. 5 Override Methods Customize or extend parent behavior for specific child types.
Figure: Java Inheritance Architecture Flow

Consider an enterprise software system that manages different types of employees: FullTimeEmployee and ContractEmployee. Both types share common attributes such as employeeId, firstName, lastName, and email. Furthermore, both require methods to calculate pay and generate profile summaries.

Without inheritance, a developer might duplicate these fields and methods across multiple class definitions. This approach creates several technical debt items:

  • Code Duplication: Identical blocks of logic exist in multiple files, multiplying the surface area for bugs.
  • Maintenance Overhead: Adding a new field, such as departmentCode, requires modifying every single employee class manually.
  • Inconsistent APIs: Different developers might name validation or calculation methods differently across classes, breaking polymorphic pipelines.

Inheritance solves this problem by enabling a parent-child relationship. Common behaviors are written once in a Superclass (or Parent class) and inherited automatically by one or more Subclasses (or Child classes).

2. Core Syntax and Mechanics

To implement inheritance in Java, use the extends keyword in the subclass declaration. The subclass inherits non-private fields and methods from the superclass.

package com.javatbrains.oops;

// Superclass (Parent)
class Employee {
    protected String employeeId;
    protected String name;

    public Employee(String employeeId, String name) {
        this.employeeId = employeeId;
        this.name = name;
    }

    public void displayDetails() {
        System.out.println("Employee ID: " + employeeId + ", Name: " + name);
    }
}

// Subclass (Child) inheriting from Employee
class FullTimeEmployee extends Employee {
    private double annualSalary;

    public FullTimeEmployee(String employeeId, String name, double annualSalary) {
        super(employeeId, name); // Calls superclass constructor
        this.annualSalary = annualSalary;
    }

    public void calculatePay() {
        System.out.println("Annual Pay for " + name + ": " + annualSalary);
    }
}

public class InheritanceDemo {
    public static void main(String[] args) {
        FullTimeEmployee emp = new FullTimeEmployee("EMP-101", "Alice Smith", 85000.0);
        emp.displayDetails(); // Inherited method
        emp.calculatePay();   // Subclass-specific method
    }
}

Output

Employee ID: EMP-101, Name: Alice Smith
Annual Pay for Alice Smith: 85000.0

When instantiating FullTimeEmployee, the JVM allocates memory for an object that contains both the superclass and subclass properties. You only need to instantiate the subclass because it encapsulates the complete state and behavior required.

3. Constructor Chaining and Execution Order

A common point of confusion for developers transitioning to Java is how constructors behave during inheritance. Constructors are not members of a class, so they are not inherited. However, the superclass constructor must execute whenever a subclass object is created to ensure proper initialization of parent-class state.

Case 1: Superclass Has a Default Constructor

If the superclass defines a default (no-argument) constructor, the Java compiler automatically inserts a call to super() as the very first statement in the subclass constructor, even if you do not write it explicitly.

package com.javatbrains.oops;

class One {
    One() {
        System.out.println("Inside One class constructor");
    }
}

class Two extends One {
    Two() {
        // Implicitly calls super();
        System.out.println("Inside Two class constructor");
    }
}

public class ConstDemo {
    public static void main(String[] args) {
        new Two();
    }
}

Output

Inside One class constructor
Inside Two class constructor

Case 2: Superclass Has a Parameterized Constructor

If a superclass does not provide a default, no-arg constructor, but defines a parameterized constructor, the compiler will throw a compilation error unless the subclass explicitly invokes an available superclass constructor using the super(arguments) syntax.

package com.javatbrains.oops;

class One1 {
    int i;

    One1(int i) {
        this.i = i;
    }

    void show() {
        System.out.println("Super class method = " + i);
    }
}

class Two2 extends One1 {
    int i; // Shadowing superclass variable for demonstration

    Two2(int x, int y) {
        super(x); // Explicit call to Superclass parameterized constructor
        this.i = y;
    }

    void show() {
        System.out.println("Sub class method i = " + i);
        System.out.println("Super class method i via super.i = " + super.i);
        super.show(); // Calling Super class show method
    }
}

public class ParamConstDemo {
    public static void main(String[] args) {
        Two2 t = new Two2(100, 200);
        t.show();
    }
}

Output

Sub class method i = 200
Super class method i via super.i = 100
Super class method = 100

4. The super Keyword Explained

The super keyword acts as a reference variable that a subclass uses to refer directly to its immediate parent class. It serves three main purposes:

  1. Accessing Parent Constructors: Invoking parent constructors using super(...). This must always be the first statement inside a subclass constructor.
  2. Accessing Hidden Fields: Disambiguating instance variables when a subclass declares a field with the exact same name as a superclass field (variable shadowing).
  3. Invoking Overridden Methods: Calling a parent version of a method that has been overridden in the child class, allowing you to augment rather than completely replace parent behavior.

5. Types of Inheritance in Java

Java supports specific types of inheritance structures to balance modeling flexibility with language design simplicity.

Inheritance Type Supported in Java? Description
Single Inheritance Yes A class extends exactly one superclass. Prevents deep, convoluted hierarchies.
Multilevel Inheritance Yes A class is derived from a class, which is itself derived from another class (A → B → C).
Hierarchical Inheritance Yes Multiple subclasses extend a single superclass (B ← A → C).
Multiple Inheritance No (for classes) A class attempting to inherit from multiple classes simultaneously. Java supports this behavior safely via interfaces with default methods.
Hybrid Inheritance Partially (via Interfaces) A combination of two or more types of inheritance.

Why Multiple Class Inheritance is Not Supported

Java deliberately omits support for multiple class inheritance to avoid architectural pitfalls such as the Diamond Problem. Imagine Class B and Class C both inherit from Class A and override a method execute(). If Class D inherits from both B and C, which version of execute() should D inherit? This ambiguity creates severe compilation and runtime unpredictability.

To achieve similar capabilities without ambiguity, Java uses interfaces. For advanced typing requirements, developers often leverage modern language features explored further in Java 17 Records and Pattern Matching with Examples.

6. Real-World Edge Cases and Gotchas

When working with inheritance in production environments, developers frequently run into specific edge cases:

Edge Case 1: Attempting to Override Private or Static Methods

Private methods belong exclusively to the declaring class and are not visible to subclasses. If a subclass defines a method with the same signature as a private method in the superclass, it is treated as a completely new, unique method in the subclass—not an override. Similarly, static methods are bound to the class rather than instances, meaning they undergo method hiding rather than polymorphic overriding.

Edge Case 2: Exception Handling Rules in Method Overriding

When a subclass overrides a superclass method, the overriding method cannot throw broader or higher-level checked exceptions than the method declared in the superclass. It can throw narrower exceptions, fewer exceptions, or no checked exceptions at all.

Edge Case 3: Memory Leaks Through Improper Subclassing

Holding references to superclass objects inside long-lived subclass collections without proper encapsulation can retain memory longer than expected. When integrating with legacy resource pools—such as those discussed in historical configurations like JNDI configuration for Tomcat 9 with Oracle—ensuring clean object lifecycles across class hierarchies prevents subtle resource leaks.

7. Troubleshooting Common Inheritance Errors

  • Compilation Error: constructor <init>` in class cannot be applied to given types
    Cause: The superclass does not have a no-arg constructor, and the subclass constructor fails to call super(...) with appropriate arguments.
    Fix: Explicitly add a call to super(arguments) as the first line of your subclass constructor.
  • Compilation Error: cyclic inheritance involving <ClassName>
    Cause: A class attempts to extend itself directly or forms a circular dependency (e.g., Class A extends Class B, and Class B extends Class A).
    Fix: Restructure your class hierarchy into a strict directed acyclic graph (DAG).

8. Summary

  • Inheritance promotes code reusability and establishes a logical taxonomy between parent (superclass) and child (subclass) classes using the extends keyword.
  • Constructors are not inherited; however, superclass constructors execute automatically or via explicit super(...) calls during subclass instantiation.
  • The super keyword provides access to hidden parent fields, overridden methods, and parent constructors.
  • Java does not support multiple class inheritance to prevent ambiguity (the Diamond Problem), but supports multiple inheritance of behavior through interfaces.
  • Private and static methods cannot be overridden polymorphically; they are hidden or restricted to their declaring scope.

Comments

Popular posts from this blog

JVM, JRE and JDK in Java

Understanding JVM, JRE, and JDK in Java Every Java developer encounters three fundamental acronyms on their first day: JVM , JRE , and JDK . Misunderstanding these foundational components leads to runtime exceptions, deployment failures, and incorrect build environments. This guide breaks down the precise architectural boundaries, memory structures, and deployment requirements of each component. ▶ Listen English (India) English (US) Hindi Telugu Tamil Kannada Malayalam Bengali Marathi Gujarati Punjabi Urdu Arabic Spanish French German Portuguese Japanese Korean Chinese (Simplified) Pick a language, then press Listen. The core problem this guide solves is ambiguous environment configuration. Developers often attempt to run production applications using a Development Kit when a Runtime Environment suffices, or they deploy platform-incompatible binaries to minimal Li...

Prime, Fibonacci and Factorial number with example in java

Mastering Prime, Fibonacci, and Factorial Algorithms in Java Prime Number Validation Workflow Prime Number Validation Workflow 1 Boundary Check Verify if the input number is less than or equal to 1. 2 Even Number Check Check if divisible by 2 and return true only if number is 2. 3 Square Root Limit Calculate integer square root as the upper loop bound. 4 Odd Factor Loop Iterate through odd integers up to limit checking divisibility. Figure: Prime Number Validation Workflow Technical coding interviews frequently test foundational algorithmic competence through three classic mathematical problems: identifying prime numbers, generating Fibonacci sequences, and calculating factorials. While these concepts originate in basic arithmetic, writing production-grade Java code to solve them requires careful attention to time complexity, memory allocation, boundary conditions, and overflow behavior. This tutorial provides rigorous, optimized Java i...

How to insert images into database using JDBC?

How to Insert Images into a Database Using JDBC Storing binary data such as images, PDFs, and application assets is a frequent requirement in enterprise software engineering. While relational databases like MySQL are optimized for structured tabular text and numeric data, they also provide robust binary storage types—specifically BLOB (Binary Large Object) variants—to handle arbitrary byte streams. When interacting with relational stores through Java, the Java Database Connectivity (JDBC) API serves as the primary bridge. ▶ Listen English (India) English (US) Hindi Telugu Tamil Kannada Malayalam Bengali Marathi Gujarati Punjabi Urdu Arabic Spanish French German Portuguese Japanese Korean Chinese (Simplified) Pick a language, then press Listen. This technical guide demonstrates how to persist image files from a local file system directly into a MySQL database usin...