Inheritance in Java Tutorial
Chapter 19 · Java Programming Series
PBA Institute 13 min read Intermediate 2024

Inheritance in Java

Inheritance lets one class acquire the properties and methods of another. It models the IS-A relationship — a Dog is an Animal. Inheritance promotes reuse, hierarchy and polymorphism, and is one of the four pillars of object-oriented programming.

Key Features

🧬

extends Keyword

Sets up parent → child relationship.

♻️

Reuse

Subclass inherits fields and methods of the parent.

Extend

Subclass can add new fields and methods.

✍️

Override

Subclass can override inherited methods.

👨‍👩‍👦

super

Access parent's fields, methods or constructor.

🚫

No Multiple

Java doesn't support multiple class inheritance (use interfaces).

Syntax

  • Syntax: class Child extends Parent { … }
  • Access parent: super.method()
  • Parent constructor: super(); at first line.
  • A class can extend only one class but implement many interfaces.

Types of Inheritance

TypeDescriptionExampleAllowed
SingleOne parent, one childDog → AnimalYes
MultilevelChain of inheritancePuppy → Dog → AnimalYes
HierarchicalOne parent, many childrenDog, Cat → AnimalYes
MultipleMultiple parent classesNo (use interfaces)

Detailed Explanation & First Example

Let's start with a hands-on example. The program below shows the core idea behind Inheritance in just a few lines of Java. Read it line by line and observe how Java executes each statement in order.

Single Inheritance
class Animal
{
    void eat() { System.out.println("Eating..."); }
}

class Dog extends Animal
{
    void bark() { System.out.println("Barking..."); }
}

class Main
{
    public static void main(String args[])
    {
        Dog d = new Dog();
        d.eat();
        d.bark();
    }
}
Output Eating...
Barking...

Examples — Beginner to Advanced

The following examples progress from simple to more practical patterns. Try each in your IDE, change the inputs and observe the output. This is the fastest way to internalize the concept.

Multilevel Inheritance
class A { void show()  { System.out.println("A"); } }
class B extends A { void show2() { System.out.println("B"); } }
class C extends B { void show3() { System.out.println("C"); } }

class Main
{
    public static void main(String args[])
    {
        C obj = new C();
        obj.show();
        obj.show2();
        obj.show3();
    }
}
Output A
B
C
Hierarchical Inheritance
class Animal { void eat() { System.out.println("Eat"); } }

class Dog extends Animal { void bark() { System.out.println("Bark"); } }
class Cat extends Animal { void meow() { System.out.println("Meow"); } }

class Main
{
    public static void main(String args[])
    {
        new Dog().eat();
        new Cat().eat();
    }
}
Output Eat
Eat
Using super()
class Vehicle
{
    Vehicle() { System.out.println("Vehicle created"); }
}

class Car extends Vehicle
{
    Car()
    {
        super();
        System.out.println("Car created");
    }
}

class Main
{
    public static void main(String args[])
    {
        new Car();
    }
}
Output Vehicle created
Car created
Method Override + super
class Bank
{
    int rate() { return 4; }
}

class SBI extends Bank
{
    int rate() { return super.rate() + 2; }
}

class Main
{
    public static void main(String args[])
    {
        System.out.println(new SBI().rate());
    }
}
Output 6

Notes & Tips

  • Java supports single, multilevel and hierarchical inheritance with classes.
  • Use interfaces to achieve multiple inheritance of type.
  • final classes cannot be extended (e.g. String).
  • private members of the parent are not directly accessible in the child.
  • Constructors are not inherited but are invoked via super().

Real-World Use Cases

Animal Hierarchy

Animal → Dog → Puppy.

Vehicle Hierarchy

Vehicle → Car → ElectricCar.

Bank Accounts

Account → SavingsAccount → SeniorSavings.

User Roles

User → Admin → SuperAdmin.

Practice Questions

Reading is not enough — practice solidifies knowledge. Try every question below in your own editor before peeking at any solution.

  • Q1. Create an Employee class and a Manager subclass with extra fields.
  • Q2. Demonstrate multilevel inheritance with three classes.
  • Q3. Override a method in the subclass and call the parent version via super.
  • Q4. Show that a private parent field is not accessible in the subclass.
  • Q5. Build a Shape → Circle / Triangle hierarchy with area().

Interview Questions

These are the most common questions asked in Java interviews on this topic. Memorize the concept, not just the answer — interviewers often follow up with edge cases.

Q1 What is inheritance?
A mechanism by which a class acquires fields and methods of another class, modeling an IS-A relationship.
Q2 Does Java support multiple inheritance?
Not with classes — only with interfaces, to avoid the diamond problem.
Q3 What is the use of the super keyword?
Access parent fields, methods, or invoke the parent constructor.
Q4 Can constructors be inherited?
No — but they are invoked from the subclass with super().
Q5 Difference between IS-A and HAS-A?
IS-A is inheritance (Dog is an Animal); HAS-A is composition (Car has an Engine).

FAQ

FAQ 1 Why doesn't Java support multiple class inheritance?
To avoid the diamond ambiguity. Use multiple interfaces instead.
FAQ 2 Are private members inherited?
Technically yes (they exist) but they are not accessible from the subclass.
FAQ 3 Can a subclass have the same field name as the parent?
Yes — the subclass field hides the parent's. Use super.field to access the parent's.
FAQ 4 What is the Object class?
The root class of every Java class — all classes implicitly extend it.
FAQ 5 When should I prefer composition over inheritance?
When the relationship is HAS-A or behavior may change; composition is more flexible.

Common Mistakes to Avoid

Even experienced developers slip on the same pitfalls. Watch out for these classic mistakes while working with Inheritance in Java:

  • Forgetting the semicolon ; at the end of statements while using Inheritance.
  • Mixing up similar method names — read Java docs before using new APIs related to Inheritance.
  • Ignoring compiler warnings — they often hint at bugs that will appear later in production.
  • Hard-coding values that should come from configuration files or environment variables.
  • Not handling edge cases: empty inputs, very large inputs, negative numbers and null references.
  • Skipping unit tests — small tests prevent big regressions, especially around control flow.

At-a-Glance

Advantages
Readable Reusable Testable Standardized
Watch Out
Edge Cases Null Safety Performance Memory
Java Version
JDK 8+ JDK 11 JDK 17 LTS JDK 21 LTS
Pair With
Constructor Interface OOP Best Practices

Best Practices

📐

Follow Conventions

Use camelCase for variables, PascalCase for classes, UPPER_SNAKE for constants.

🧪

Write Tests

Cover happy path and edge cases with JUnit before shipping changes to production.

🧹

Keep Methods Short

A method should do one thing and fit on a single screen. Refactor when it grows.

🔍

Validate Inputs

Never trust user input. Validate at the boundary, fail fast and log meaningfully.

📝

Comment the Why

Comments should explain why a decision was made — not what the code does line by line.

♻️

Refactor Often

Small frequent refactors are cheap and safe; big rewrites are risky and expensive.

Pro Tips

TIP 01 Use clear, descriptive identifiers when writing code involving Inheritance — your future self will thank you.
TIP 02 Run small experiments in jshell (Java's REPL) to test ideas before committing them to a project.
TIP 03 Read the official java.lang and java.util documentation. The standard library is huge and surprisingly powerful.
TIP 04 Combine this topic with unit testing (JUnit 5) — it forces you to think about edge cases.
TIP 05 Practice with online judges (HackerRank, LeetCode) to internalise the patterns used in real interviews.

Quick Reference

Keyword / ConceptMeaningUsed ForJava Since
InheritanceInheritance conceptCore Java1.0
classBlueprint of objectsOOP1.0
staticClass-level memberUtilities1.0
finalConstant / no overrideImmutability1.0
publicAccessible everywhereAPI exposure1.0
privateClass-only accessEncapsulation1.0

Related Topics

PREV Constructor — strengthens your understanding of the previous building block.
NEXT Interface — the natural progression after mastering Inheritance.
OOP Object Oriented Programming — Class, Object, Inheritance, Polymorphism, Encapsulation, Abstraction.
DSA Data Structures & Algorithms — apply this topic in real coding-interview challenges.
STD LIB Java Standard Library — explore java.util, java.lang and java.io.

Summary

Inheritance models the IS-A relationship and lets a class reuse and extend another. Java supports single, multilevel and hierarchical inheritance via extends; multiple inheritance comes from interfaces. Use super to call parent constructors and methods, and prefer composition when inheritance forces a wrong hierarchy.

Continue Learning