Inheritance in Java


What is Inheritance?

Inheritance allows one class (child) to acquire properties and behaviors (fields and methods) of another class (parent).
It's like "Child inherits features from Parent".

Syntax
    
    class Parent {
        // fields and methods
    }

    class Child extends Parent {
        // additional fields and methods
    }
    
    

extends keyword is used to inherit from a class.

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

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

    // Main class
    public class Main {
        public static void main(String[] args) {
            Dog d = new Dog();
            d.eat();   // inherited method
            d.bark();  // own method
        }
    }
    
    
Output:
    
    This animal eats food.
    Dog barks.
    
    
Why use Inheritance?
  • Reusability: Avoid writing the same code again.
  • Extensibility: Easily add new features.
  • Readability: Code structure becomes more logical.
Types of Inheritance in Java
Type Supported in Java? Example
Single Yes One child → one parent
Multilevel Yes Class C inherits from B, B from A
Hierarchical Yes Multiple classes inherit from one parent
Multiple (direct) No Java doesn't support this (but you can use interfaces)
Multilevel Example
    
    class A {
        void displayA() {
            System.out.println("A class");
        }
    }

    class B extends A {
        void displayB() {
            System.out.println("B class");
        }
    }

    class C extends B {
        void displayC() {
            System.out.println("C class");
        }
    }

    public class Test {
        public static void main(String[] args) {
            C obj = new C();
            obj.displayA();  // from A
            obj.displayB();  // from B
            obj.displayC();  // from C
        }
    }
    
    
super Keyword (used in Inheritance)
  • super is used to refer to the parent class.
  • You can use it to:
    • Call parent class methods: super.methodName();
    • Call parent class constructor: super();
Example:
    
    class Animal {
        Animal() {
            System.out.println("Animal constructor");
        }
    }

    class Dog extends Animal {
        Dog() {
            super(); // calls parent constructor
            System.out.println("Dog constructor");
        }
    }
    
    
Access Modifiers in Inheritance
Modifier Inherited in Child?
public Yes
protected Yes
private No
default (no modifier) Only in same package

"Inheritance = Parent gives code to child. Child gets all the features and adds new ones too."