Object Oriented Programming with Java

⌘K
  1. Home
  2. Docs
  3. Object Oriented Programmi...
  4. Inheritance and Interface
  5. Inheritance in Java

Inheritance in Java

Learn everything about Inheritance in Java — its concept, types, syntax, and real-world examples. Master how Java inheritance enhances code reusability and object-oriented design.


Introduction

In the world of Object-Oriented Programming (OOP), inheritance is one of the most fundamental and powerful concepts. It allows a new class to reuse, extend, and enhance the properties and behaviors of an existing class.

In Java, inheritance not only promotes code reusability but also ensures a clean, organized, and scalable software design. Whether you’re developing enterprise applications or learning Java as a beginner, understanding inheritance is crucial to writing efficient, maintainable, and modular code.

In this article, we’ll explore the concept of inheritance in Java, its syntax, types, advantages, and real-world examples, along with practical code implementations.


What is Inheritance in Java?

Inheritance in Java is a mechanism where one class (called the subclass or child class) derives the properties and methods of another class (called the superclass or parent class).

It represents an “is-a” relationship — meaning the child class is a specific type of the parent class.

Example:

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

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

public class InheritanceExample {
    public static void main(String[] args) {
        Dog d = new Dog();
        d.eat();  // Inherited method
        d.bark(); // Own method
    }
}

Output:

This animal eats food.
The dog barks.

Here, the Dog class inherits the method eat() from the Animal class, demonstrating the core idea of inheritance.


Key Terms in Java Inheritance

  • Superclass (Parent Class): The class whose properties are inherited.
  • Subclass (Child Class): The class that inherits from another class.
  • extends Keyword: Used to inherit from a class.
  • super Keyword: Used to refer to the parent class or call its constructor.
  • Method Overriding: Redefining a parent class method in the child class.

Why Use Inheritance in Java?

Inheritance simplifies programming and improves productivity by enabling:

  • Code Reusability: You can reuse parent class code instead of writing it again.
  • Method Overriding: Subclasses can modify behavior as needed.
  • Polymorphism: Enhances flexibility and maintainability.
  • Improved Organization: Establishes clear class hierarchies for complex projects.

Syntax of Inheritance in Java

The extends keyword establishes an inheritance relationship between two classes.

class ParentClass {
    // Parent members
}

class ChildClass extends ParentClass {
    // Child-specific members
}

Types of Inheritance in Java

Java supports different forms of inheritance to meet varying design needs. However, multiple inheritance is restricted to avoid ambiguity (commonly known as the Diamond Problem).

1. Single Inheritance

A subclass inherits from one superclass.

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

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

Use Case: Basic inheritance where one class extends another.


2. Multilevel Inheritance

A class is derived from a subclass, forming a chain of inheritance.

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

class Parent extends GrandParent {
    void sayHello() {
        System.out.println("Hello from Parent");
    }
}

class Child extends Parent {
    void introduce() {
        System.out.println("Hello from Child");
    }
}

Use Case: Hierarchical relationships like family or company structures.


3. Hierarchical Inheritance

Multiple classes inherit from a single parent class.

class Vehicle {
    void start() {
        System.out.println("Vehicle started");
    }
}

class Car extends Vehicle {
    void drive() {
        System.out.println("Car is driving");
    }
}

class Bike extends Vehicle {
    void ride() {
        System.out.println("Bike is riding");
    }
}

Use Case: When several subclasses share common functionality from a parent class.


4. Multiple Inheritance (via Interfaces)

Java doesn’t allow multiple inheritance with classes but supports it through interfaces.

interface Engine {
    void startEngine();
}

interface Fuel {
    void fillFuel();
}

class Car implements Engine, Fuel {
    public void startEngine() {
        System.out.println("Engine started.");
    }
    public void fillFuel() {
        System.out.println("Fuel filled.");
    }
}

Use Case: Combine functionalities from multiple sources safely.


5. Hybrid Inheritance (Through Interfaces)

Hybrid inheritance is a mix of multiple and multilevel inheritance. In Java, it’s achieved only using interfaces.


Understanding the super Keyword

The super keyword is used to access members of the parent class. It helps avoid confusion when subclass and superclass have methods or variables with the same name.

Example:

class Animal {
    String type = "Animal";
}

class Dog extends Animal {
    String type = "Dog";

    void printType() {
        System.out.println(super.type); // Access parent property
    }
}

Output:

Animal

Method Overriding in Inheritance

Method Overriding allows a subclass to modify the behavior of a method inherited from its parent.

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

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

When called, the subclass method overrides the parent’s method.


Constructors and Inheritance

Constructors are not inherited, but the parent constructor can be called using super().

class Parent {
    Parent() {
        System.out.println("Parent Constructor");
    }
}

class Child extends Parent {
    Child() {
        super(); // calls Parent constructor
        System.out.println("Child Constructor");
    }
}

Output:

Parent Constructor
Child Constructor

Advantages of Inheritance in Java

  • Enhances code reusability and modularity
  • Simplifies debugging and maintenance
  • Promotes hierarchical classification
  • Enables runtime polymorphism
  • Reduces code redundancy

Limitations of Inheritance

  • Tight coupling: Changes in superclass can affect subclasses.
  • Complex hierarchies: Deep inheritance trees can become difficult to manage.
  • Constructor constraints: Parent constructors must be explicitly called.
  • Limited flexibility: Java doesn’t support multiple class inheritance.

Real-World Example of Inheritance in Java

Consider a banking system where multiple account types share common functionality.

class Account {
    double balance = 1000.0;

    void deposit(double amount) {
        balance += amount;
        System.out.println("Deposited: $" + amount);
    }
}

class SavingsAccount extends Account {
    void addInterest() {
        balance += balance * 0.05;
        System.out.println("Interest added. Balance: $" + balance);
    }
}

public class BankApp {
    public static void main(String[] args) {
        SavingsAccount s = new SavingsAccount();
        s.deposit(500);
        s.addInterest();
    }
}

Output:

Deposited: $500.0
Interest added. Balance: $1575.0

This demonstrates real-world inheritance, where SavingsAccount inherits deposit() from Account and extends it with an interest feature.


Conclusion

Inheritance in Java is one of the cornerstones of object-oriented programming, allowing developers to build modular, reusable, and extensible code. By understanding the concept, syntax, and various inheritance types, you can design cleaner architectures and improve application scalability.

Mastering inheritance sets a solid foundation for understanding polymorphism, abstraction, and encapsulation — the other pillars of OOP in Java.


Frequently Asked Questions (FAQs)

1. What is inheritance in Java?

Inheritance in Java allows one class to acquire properties and methods from another class, promoting code reusability and modular design.

2. What keyword is used for inheritance in Java?

The extends keyword is used to inherit from a parent class, while implements is used for interfaces.

3. Can Java support multiple inheritance?

No, Java doesn’t support multiple inheritance with classes to avoid ambiguity, but it can be achieved using interfaces.

4. Are constructors inherited in Java?

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

5. What are the main advantages of inheritance?

Key benefits include code reusability, reduced redundancy, and improved maintainability.

Tags , , , , , , ,

How can we help?

Leave a Reply

Your email address will not be published. Required fields are marked *