Inheritance in Java Explained with Real Examples, Output & Why Multiple Inheritance is Not Supported

 

Inheritance in Java – Complete Guide

Explained with Full Examples and Output

? What is Inheritance in Java?

Inheritance is one of the most important features of Object-Oriented Programming (OOP) in Java. It allows one class (called the child or subclass) to inherit the properties and behaviors (fields and methods) of another class (called the parent or superclass). This helps in code reusability, method overriding, and makes the program easier to manage and extend.

🏗️ Java Inheritance Types

Interactive Visual Guide to Object-Oriented Programming Concepts

✅ Single Inheritance

One child class inherits from one parent class

Parent Class
Child Class
class Animal { }
class Dog extends Animal { }
❌ Multiple Inheritance

NOT Supported in Java

(Use Interfaces instead)

Parent A
Parent B
Child Class
// This won't work in Java
class Child extends A, B { }
🔗 Multilevel Inheritance

Chain of inheritance: Grandparent → Parent → Child

Grandparent
Parent
Child
class Animal { }
class Mammal extends Animal { }
class Dog extends Mammal { }
🌳 Hierarchical Inheritance

One parent class, multiple child classes

Parent Class
Child A
Child B
Child C
class Animal { }
class Dog extends Animal { }
class Cat extends Animal { }
class Bird extends Animal { }

💡 Key Takeaways

✅ Supported in Java:
Single, Multilevel, Hierarchical
❌ Not Supported:
Multiple Inheritance (use Interfaces)
🎯 Best Practice:
Prefer composition over inheritance

Why Use Inheritance in Java?

Code Reusability: No need to write the same code again and again.
Method Overriding: Child class can modify the method of the parent class.
Runtime Polymorphism: Enables dynamic method dispatch.
Organized Code: Helps in maintaining and upgrading the code.

📋 Types of Inheritance in Java

1. Single Inheritance 2. Multilevel Inheritance 3. Hierarchical Inheritance
Note: Java does not support Multiple Inheritance using classes to avoid ambiguity, but it can be achieved using interfaces.

1 Single Inheritance in Java

In this type, one class inherits another class.

Example:
class Animal {
    void sound() {
        System.out.println("Animals make sound");
    }
}

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

public class Main {
    public static void main(String[] args) {
        Dog d = new Dog();
        d.sound();  // From Animal class
        d.bark();   // From Dog class
    }
}
Output:
Animals make sound
Dog barks
Explanation:
  • Dog class extends Animal, so it can use the sound() method from the Animal class.
  • This is called single inheritance because only one parent is inherited by one child.

2 Multilevel Inheritance in Java

In this type, a class inherits another class, which in turn inherits another class.

Example:
class Animal {
    void eat() {
        System.out.println("This animal eats food");
    }
}

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

class Puppy extends Dog {
    void weep() {
        System.out.println("Puppy weeps");
    }
}

public class Main {
    public static void main(String[] args) {
        Puppy p = new Puppy();
        p.eat();   // From Animal
        p.bark();  // From Dog
        p.weep();  // From Puppy
    }
}
Output:
This animal eats food
Dog barks
Puppy weeps
Explanation:
  • Puppy inherits from Dog, and Dog inherits from Animal.
  • All properties and methods are available to the Puppy class.

3 Hierarchical Inheritance in Java

In this type, multiple classes inherit from one parent class.

Example:
class Animal {
    void sound() {
        System.out.println("Animals have different sounds");
    }
}

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

class Cat extends Animal {
    void meow() {
        System.out.println("Cat meows");
    }
}

public class Main {
    public static void main(String[] args) {
        Dog d = new Dog();
        Cat c = new Cat();
        
        d.sound();
        d.bark();

        c.sound();
        c.meow();
    }
}
Output:
Animals have different sounds
Dog barks
Animals have different sounds
Cat meows
Explanation:
  • Dog and Cat both extend the Animal class.
  • This is known as hierarchical inheritance.

4 Multiple Inheritance Using Interfaces

Java does not support multiple inheritance with classes to prevent ambiguity (like the Diamond Problem), but it supports multiple inheritance using interfaces.

Example:
interface A {
    void methodA();
}

interface B {
    void methodB();
}

class C implements A, B {
    public void methodA() {
        System.out.println("Method A");
    }
    
    public void methodB() {
        System.out.println("Method B");
    }
}

public class Main {
    public static void main(String[] args) {
        C obj = new C();
        obj.methodA();
        obj.methodB();
    }
}
Output:
Method A
Method B
Explanation:
  • Class C implements two interfaces, A and B.
  • No ambiguity since both are interfaces and Java handles them well.

🔑 Super Keyword in Inheritance

super is used to refer to the parent class. It can be used to:

1. Call parent class constructor.
2. Access parent class methods or variables.
Example:
class Animal {
    String color = "White";

    Animal() {
        System.out.println("Animal is created");
    }

    void displayColor() {
        System.out.println("Animal color: " + color);
    }
}

class Dog extends Animal {
    String color = "Black";

    Dog() {
        super(); // calls Animal constructor
        System.out.println("Dog is created");
    }

    void printColor() {
        System.out.println("Dog color: " + color);
        System.out.println("Animal color using super: " + super.color);
    }
}

public class Main {
    public static void main(String[] args) {
        Dog d = new Dog();
        d.printColor();
    }
}
Output:
Animal is created
Dog is created
Dog color: Black
Animal color using super: White

🔄 Method Overriding in Inheritance

When a subclass provides its own version of a method from the superclass, it's called method overriding.

Example:
class Animal {
    void sound() {
        System.out.println("Animal makes a sound");
    }
}

class Dog extends Animal {
    void sound() {
        System.out.println("Dog barks");
    }
}

public class Main {
    public static void main(String[] args) {
        Animal a = new Dog();
        a.sound();  // Calls Dog's overridden method
    }
}
Output:
Dog barks
Explanation:
  • Though the reference is of type Animal, the object is Dog.
  • The Dog class's method is executed due to runtime polymorphism.

⚠️ Why Java Does Not Support Multiple Inheritance with Classes

Java does not support multiple inheritance with classes directly, and there's a solid reason behind it—to avoid ambiguity and complexity in code. This problem is famously known as the Diamond Problem.

What is the Diamond Problem?

Imagine you have three classes:

class A {
    void show() {
        System.out.println("A's show method");
    }
}

class B extends A {
    void show() {
        System.out.println("B's show method");
    }
}

class C extends A {
    void show() {
        System.out.println("C's show method");
    }
}

Now, what if you try to create a class D that extends both B and C?

class D extends B, C {  // Not allowed in Java
    // Confusion: Which show() should D inherit?
}
Problem:
Both B and C have their own versions of the show() method. If class D inherits from both, the compiler gets confused—which show() method should be called?
  • From B?
  • Or from C?

This ambiguity leads to confusion, bugs, and makes the code harder to maintain and understand.

🔧 How Java Solves Multiple Inheritance

Understanding Java's Approach to Avoiding the Diamond Problem

🎯 Java's Solution Strategy

Single Inheritance

with Classes

🔗

Multiple Inheritance

through Interfaces

Key Insight: Interfaces in Java only declare methods, they don't implement them. So when a class implements multiple interfaces, it must provide its own implementation, eliminating any ambiguity!

💡 Example Using Interfaces (No Ambiguity)

Interface A
void show();
Interface B
void show();
implements
Class C
Provides its own show() implementation
// Interface A
interface
A
{
void
show
();
}
// Interface B
interface
B
{
void
show
();
}
// Class implementing both interfaces
class
C
implements
A
,
B
{
public void
show
() {
System
.
out
.
println
(
"C's show method"
);
}
}
📤 Output:
C's show method

🤔 Why no confusion?

Because class C provides its own implementation of show(), and interfaces do not carry method bodies (until Java 8, which introduced default methods, but even those can be overridden to resolve conflicts).

🎯 Conclusion

🚫
Prevent Ambiguity
(like the Diamond Problem)
Keep Code Clean
Simple and bug-free
🏗️
Better Design
Using composition & interfaces

Instead of forcing multiple inheritance, Java gives you interfaces and default methods for flexibility—without compromising clarity and maintainability.

🌟 Final Words on Inheritance in Java

Inheritance helps reduce code duplication, enables polymorphism, and makes programs modular and maintainable. Java supports different types of inheritance (except multiple inheritance with classes) and uses powerful features like super and method overriding to give developers better control over code behavior.

❓ FAQs about Inheritance in Java

1. What is the main purpose of inheritance in Java?

To allow a class to use the properties and methods of another class, reducing redundancy and improving code structure.

2. Can we inherit constructors in Java?

Constructors are not inherited, but you can call the parent constructor using the super() keyword.

3. What is the difference between "extends" and "implements"?

extends is used to inherit from a class.

implements is used to implement an interface.

4. Can a class extend more than one class in Java?

No, Java does not support multiple inheritance using classes to avoid conflicts.

5. How do you achieve multiple inheritance in Java?

You can use interfaces to achieve multiple inheritance in Java.

🔗 extends vs implements

Understanding Java's Key Inheritance Keywords

extends

For Class Inheritance

Parent Class
extends
Child Class

✨ Key Features:

  • Inherits all public/protected methods and fields
  • Can override parent methods
  • Single inheritance only (one parent class)
  • Child IS-A relationship with parent
class
Animal
{
void
eat
() { ... }
}

class
Dog
extends
Animal
{
void
bark
() { ... }
}
implements

For Interface Implementation

Interface A
Interface B
implements
Implementation Class

🔧 Key Features:

  • Must implement all interface methods
  • Can implement multiple interfaces
  • Provides contract/blueprint
  • Class CAN-DO relationship with interface
interface
Flyable
{
void
fly
();
}

class
Bird
implements
Flyable
{
public void
fly
() { ... }
}

📊 Detailed Comparison

Aspect extends implements
Purpose Class Inheritance Interface Implementation
Multiple Support ❌ No (Single only) ✅ Yes (Multiple)
Method Implementation Inherits existing methods Must implement all methods
Access Modifiers Any (public, protected, private) Public only (in implementation)
Relationship Type IS-A relationship CAN-DO relationship
Variables/Fields Inherits parent's fields Only static final constants

💻 Practical Examples

🟢 Using extends

// Parent class
class Vehicle {
protected String brand;
public void start() {
System.out.println("Vehicle started");
}
}

// Child class
class Car extends Vehicle {
public void honk() {
System.out.println("Car honks!");
}
}
Result: Car inherits start() method and brand field

🔵 Using implements

// Interfaces
interface Flyable {
void fly();
}

interface Swimmable {
void swim();
}

// Implementation class
class Duck implements Flyable, Swimmable {
public void fly() {
System.out.println("Duck flies!");
}
public void swim() {
System.out.println("Duck swims!");
}
}
Result: Duck must implement both fly() and swim() methods


Post a Comment

0 Comments