0
0
Javaprogramming~5 mins

Inheritance limitations in Java

Choose your learning style9 modes available
Introduction

Inheritance lets one class get features from another. But it has limits to keep code clear and safe.

When you want to understand why a class can't inherit from multiple classes in Java.
When you need to know why some methods can't be overridden.
When you want to avoid problems caused by deep or complex inheritance chains.
When designing classes and deciding between inheritance and other ways like interfaces.
When debugging issues caused by inheritance rules.
Syntax
Java
class Parent {
    void show() {
        System.out.println("Parent class method");
    }
}

class Child extends Parent {
    // Child inherits show() method
}

Java allows only one direct parent class (single inheritance).

Some classes or methods can be marked final to prevent inheritance or overriding.

Examples
A final class cannot be inherited.
Java
final class FinalClass {
    void display() {
        System.out.println("Can't inherit this class");
    }
}

// This will cause an error:
// class Child extends FinalClass {}
A final method cannot be overridden by child classes.
Java
class Parent {
    final void show() {
        System.out.println("Can't override this method");
    }
}

class Child extends Parent {
    // Trying to override show() here will cause an error
}
Java does not support multiple inheritance of classes.
Java
class A {}
class B {}

// Java does not allow:
// class C extends A, B {}
Sample Program

This program shows a normal inheritance from Parent to Child. It also shows that a final class like FinalParent cannot be inherited (commented out to avoid error).

Java
class Parent {
    void greet() {
        System.out.println("Hello from Parent");
    }
}

final class FinalParent {
    void greet() {
        System.out.println("Hello from FinalParent");
    }
}

class Child extends Parent {
    // Inherits greet()
}

// Uncommenting below will cause compile error
// class Child2 extends FinalParent {}

public class Main {
    public static void main(String[] args) {
        Child c = new Child();
        c.greet();
    }
}
OutputSuccess
Important Notes

Java uses final keyword to stop inheritance or method overriding.

Multiple inheritance of classes is not allowed to avoid confusion and errors.

Use interfaces if you need to inherit from multiple types.

Summary

Java allows only single inheritance of classes.

final classes and methods cannot be inherited or overridden.

Inheritance limits help keep code simple and avoid mistakes.