Published on

Mastering Inheritance in OOP - Concepts, Examples, Types & Interview Prep

Inheritance is an object-oriented programming principle where a class acquires properties and behaviors (fields and methods) from another class.

This allows the creation of a hierarchy where child (subclass) objects can reuse, extend, or customize code from their parent (superclass).

πŸ“– Formal Definition

Inheritance is a mechanism that allows one class to inherit the fields and methods of another class, enabling code reuse, polymorphism, and hierarchical relationships.

🧱 Key Characteristics of Inheritance

FeatureDescription
Code ReusabilityShare common functionality in parent class
ExtensibilityAdd or modify behavior in the child class
Hierarchy SupportOrganize classes in logical structures
Polymorphism BaseEnables method overriding and dynamic behavior
Single Source of TruthAvoid duplicate code in multiple classes

πŸ› οΈ Basic Java Example

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

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

public class Main {
    public static void main(String[] args) {
        Dog dog = new Dog();
        dog.eat();  // inherited
        dog.bark(); // subclass-specific
    }
}

πŸ‘ͺ Real-Life Analogy

Inheritance in Real Life:

  • A child inherits traits like eye color or blood type from parents.
  • In software, a subclass inherits methods and properties from its superclass.

πŸ“Œ Types of Inheritance in Java

TypeDescriptionSupported in Java
SingleOne subclass inherits one superclassβœ… Yes
MultilevelClass inherits a class that also inherited another classβœ… Yes
HierarchicalMultiple classes inherit from a single superclassβœ… Yes
MultipleOne class inherits from multiple classes❌ (use Interfaces)
HybridCombination of multiple types (handled using interfaces in Java)βœ… With Interfaces

πŸ“š Java Syntax

class Parent {
    void show() {
        System.out.println("Parent method");
    }
}

class Child extends Parent {
    void display() {
        System.out.println("Child method");
    }
}

Use the extends keyword to establish inheritance.

πŸ”„ Method Overriding

class Animal {
    void sound() {
        System.out.println("Generic Animal Sound");
    }
}

class Cat extends Animal {
    @Override
    void sound() {
        System.out.println("Meow");
    }
}

Allows runtime polymorphism.

🧠 Key Interview Points

  • Inheritance promotes reusability and reduces redundancy.
  • Constructors are not inherited, but super() can call parent constructor.
  • Private members of a class are not inherited directly.
  • Java does not support multiple inheritance with classes (to avoid ambiguity like the Diamond Problem).
  • Java allows multiple inheritance using interfaces.

βš–οΈ Inheritance vs Composition vs Interface

FeatureInheritanceCompositionInterface
Code Reuseβœ… Yes (via parent class)βœ… Yes (via object references)βœ… Yes (via contract enforcement)
Flexibility❌ Rigidβœ… Highβœ… High
Tight Couplingβœ… Tight❌ Loose❌ Loose
Multiple Support❌ No (classes)βœ… Yesβœ… Yes
Use WhenIS-A relationshipHAS-A relationshipNeed for abstraction across classes

βœ… Best Practices

  • Favor composition over inheritance when behavior is not strictly hierarchical.
  • Keep your class hierarchies shallow to maintain simplicity.
  • Avoid deep inheritance trees β€” they are hard to maintain and test.
  • Use final to prevent inheritance when necessary.
  • Use interfaces when multiple behavior contracts are needed.

❓ Interview Questions with Answers

Q1. What is inheritance in OOP? A: A mechanism by which a subclass acquires the properties and behavior of a superclass.

Q2. Can private fields be inherited? A: No, private members are not accessible in the subclass, but they exist in memory.

Q3. What is method overriding? A: Redefining a superclass method in a subclass with the same signature.

Q4. Why Java doesn’t support multiple inheritance with classes? A: To avoid ambiguity (Diamond Problem). Interfaces solve this limitation.

Q5. What's the difference between super() and this()? A: super() calls the parent constructor; this() calls another constructor in the same class.

πŸ” Common Use Cases of Inheritance

Use CaseExample
Shared FunctionalityVehicle β†’ Car, Bike
Reusable LogicUser β†’ Admin, Guest
Behavioral PolymorphismShape β†’ Circle, Rectangle
Framework DesignSpring, Hibernate use inheritance

πŸ”š Summary

  • Inheritance is key to code reusability and object hierarchy.
  • It forms the backbone of polymorphism and modular class design.
  • Use it wisely with abstract classes or interfaces, and prefer shallow, meaningful class hierarchies.