TeachingBee

Hierarchical Inheritance in Java with Examples

Hierarchical Inheritance in Java with Examples

In OOPS, Inheritance is a fundamental concept in programming that allows you to create new classes based on existing ones. It enables a new class, known as the “child” or “subclass” to inherit the attributes and behaviours of an existing class, known as the “parent” or “superclass.”

In essence, inheritance allows you to build upon what’s already defined in a class, reusing and extending its features. This helps organise and structure code, making it more efficient and maintainable.

In this article we will see that what is hierarchical inheritance in Java and also see some of the example of hierarchical inheritance in Java.

What is Hierarchical Inheritance In Java?

Hierarchical Inheritance In Java

Hierarchical inheritance in Java involves the creation of a class hierarchy where you have a single parent class, known as the superclass, and multiple child classes, known as subclasses. All of these subclasses inherit attributes and behaviours from the same parent class.

  1. Superclass (Parent Class): This is the top-level class in the hierarchy. It defines common attributes and behaviours that are shared by all the subclasses. In the context of hierarchical inheritance, there is only one superclass.
  2. Subclasses (Child Classes): These are the classes that inherit from the superclass. Each subclass extends the superclass by adding its own unique attributes and behaviours in addition to the ones inherited from the superclass. Multiple subclasses can exist in a hierarchical inheritance.

Let’s understand using hierarchical inheritance example in Java.

Hierarchical Inheritance Example In Java

To understand hierarchical inheritance in Java program better let’s see Vehicle hierarchical inheritance program in Java.

We can create a parent class called Vehicle that represents the common attributes and behaviours of all types of vehicles:

// Vehicle Class

public class Vehicle {

  private String engineType;

  private int wheelCount;

  public void startEngine() {
    //starting engine logic
  }

  public void applyBrakes() {
    //braking logic
  }

}

The Vehicle class contains engineType, wheelCount fields, and startEngine(), applyBrakes() methods that any vehicle would need. We can now create child classes Car and Bike that inherit from the parent Vehicle class:

// Sub Classes
public class Car extends Vehicle {

  private int numDoors;

  public void openDoors() {
    //door opening logic
  }

}

public class Bike extends Vehicle {

  private int numGears;

  public void paddle() {
    //paddle logic
  }

}

The Car and Bike classes use the extends keyword to establish the hierarchical inheritance relationship with the Vehicle parent.

They inherit the engineType, wheelCount, startEngine() and applyBrakes() members from Vehicle without having to redefine them. At the same time, they define their own fields and methods like numDoors, openDoors(), numGears, paddle() that are specific to cars and bikes respectively.

This demonstrates hierarchical inheritance in a simple vehicle hierarchy example. Multiple subclasses leverage reused logic from the single parent while having their own customized features.

Real World Example Of Hierarchical Inheritance In Java

Let’s look at some of the real world example of Hierarchical Inheritance In Java

Game Development

In game development, hierarchical inheritance is a powerful concept used to create different character types while efficiently managing shared attributes and behaviours. Here’s how it works:

// Base Character class

class Character {
    String name;
    int health;
    int attackPower;

    void takeDamage(int damage) {
        health -= damage;
    }
}
  • The Character class acts as the foundation for all game characters. It contains common attributes such as name, health, and attackPower.
  • The takeDamage(int damage) method allows all characters to receive damage and update their health.
// Specific character types inheriting from Character

class Soldier extends Character {
    // Additional attributes or methods specific to soldiers
    void meleeAttack() {
        // Melee attack logic
    }
}

class Archer extends Character {
    // Additional attributes or methods specific to archers
    void shootArrow() {
        // Shooting arrow logic
    }
}

class Mage extends Character {
    // Additional attributes or methods specific to mages
    void castSpell() {
        // Spell casting logic
    }
}
  • Specific character types like Soldier, Archer, and Mage inherit all the attributes and methods from the Character class.
  • They can also add their own unique attributes and methods. For example, Soldier has a meleeAttack() method, while Archer has a shootArrow() method.

Web Development

In web development, hierarchical inheritance simplifies the management of different content types while reusing essential information. Here’s an example:

// Parent Content class for articles, pages, etc.
class Content {
    String title;
    String text;
    String author;
}

The Content class serves as the common base for various types of content on a website, including attributes like title, text, and author.

// Specific content types inheriting from Content

class BlogPost extends Content {
    // Additional attributes specific to blog posts
    String[] tags;
}

class Article extends Content {
    // Additional attributes specific to articles
    String publicationDate;
}

class Page extends Content {
    // Additional attributes specific to pages
    int pageCount;
}
  • Content types like BlogPost, Article, and Page inherit core attributes from the Content class.
  • They extend the hierarchy by introducing their unique attributes. For example, BlogPost includes an array of tags, while Article has a publicationDate.

Graphical Interface (GUI) Development

In graphical user interface (GUI) development, hierarchical inheritance streamlines the creation of reusable components with specific functionalities. Here’s a simplified example:

// Base Component class for graphical elements
class Component {
    int size;
    int positionX;
    int positionY;
    String color;

    // Common methods for all components
    void draw() {
        // Drawing logic
    }
}

The Component class defines the fundamental properties shared by all graphical elements in the GUI, such as size, positionX, positionY, and color.

// Specific component types inheriting from Component
class Button extends Component {
    // Additional methods and attributes specific to buttons
    void click() {
        // Button click logic
    }
}

class TextBox extends Component {
    // Additional methods and attributes specific to text boxes
    void setText(String text) {
        // Set text logic
    }
}

class Panel extends Component {
    // Additional methods and attributes specific to panels
    void addComponent(Component component) {
        // Add component logic
    }
}
  • Component types like Button, TextBox, and Panel inherit the fundamental properties and methods from the Component class.
  • They specialise by introducing their unique methods and attributes. For instance, Button has a click() method, TextBox has a setText(String text) method, and Panel can manage a collection of components with addComponent(Component component).

Hierarchical Inheritance in Java Program

Hierarchical inheritance in Java is a scenario where one parent class is inherited by multiple child classes. It’s a way to create a hierarchy of classes that share common features while also introducing specific features in the child classes.

Here’s an example to illustrate hierarchical inheritance:

  1. Parent Class (Animal): A base class that includes properties and methods common to all animals.
  2. Child Classes (Dog, Cat, Bird): These classes inherit from the Animal class and can have their own specific properties and methods in addition to what they inherit from Animal.

Java Code Example:

// Parent class
class Animal {
    void eat() {
        System.out.println("Eating...");
    }
}

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

// Child class 2
class Cat extends Animal {
    void meow() {
        System.out.println("Meowing...");
    }
}

// Child class 3
class Bird extends Animal {
    void fly() {
        System.out.println("Flying...");
    }
}

// Main class to test the inheritance
public class TestInheritance {
    public static void main(String args[]) {
        Dog d = new Dog();
        Cat c = new Cat();
        Bird b = new Bird();

        d.eat();
        d.bark();

        c.eat();
        c.meow();

        b.eat();
        b.fly();
    }
}

Output

Eating...
Barking...
Eating...
Meowing...
Eating...
Flying...

In this example:

  • When the Dog object d calls eat() and bark(), it first prints "Eating..." from the inherited eat() method in the Animal class, followed by "Barking..." from its own bark() method.
  • Similarly, the Cat object c calls eat() and meow(), resulting in "Eating..." and "Meowing..." respectively.
  • The Bird object b calls eat() and fly(), outputting "Eating..." and "Flying...".

This example shows how hierarchical inheritance allows for code reusability and organisation by having a common base class from which other classes derive common behaviours and properties.

How is Hierarchical Inheritance Useful?

Hierarchical inheritance in Java program provides several advantages when used appropriately:

Eliminates Code Duplication

  • Common attributes and behaviours defined in a parent class are inherited by all child classes.
  • This eliminates duplicate code as child classes can rely on the inherited features.
  • For example, a Vehicle class contains shared logic like startEngine() that Car and Bike subclasses inherit without rewriting.

Clean Hierarchical Relationships

  • Hierarchical inheritance allows modelling relationships between classes that mirror real-world taxonomies.
  • For example, Vehicle superclass is a general parent category with subclasses Car, Bike being more specific.

Improved Organization

  • Hierarchical inheritance provides structure that makes complex software more manageable.
  • Related classes are organised under parent-child relationships making them easier to understand.
  • This is especially useful when designing large object-oriented systems.

Easier Maintenance

  • When a change is needed in shared parent class logic, it can be done once and inherited everywhere.
  • For example, changing how startEngine() works in Vehicle will automatically apply to all subclasses.
  • This makes maintenance simpler compared to changing duplicate code everywhere.

Key TakeAways

To Conclude

  1. Hierarchical inheritance in Java program involves the creation of a class hierarchy where you have a single parent class and multiple child classes.
  2. Child classes automatically inherit attributes and behaviors from parent classes. This eliminates duplicate code.
  3. Child classes can override inherited methods from the parent to provide specialized implementations.
  4. In addition to inherited members, child classes can declare their own unique fields and methods.
  5. Hierarchical inheritance structures code logically, mimicking real-world taxonomies. This makes large systems more organized and maintainable.

Checkout more Java Tutorials here.

FAQ

What is a hierarchy in Java?

What is hierarchical abstraction in Java?

What is a multilevel inheritance?

What are different types of inheritance?

90% of Tech Recruiters Judge This In Seconds! 👩‍💻🔍

Don’t let your resume be the weak link. Discover how to make a strong first impression with our free technical resume review!

Related Articles

ascii value in java

Print ASCII Value in Java

In this article we will into the ASCII table in C, exploring its various character sets—from control characters to printable characters, including letters, digits, and special symbols—and demonstrates how to

data hiding in java

Data Hiding In Java

In this article we will discuss data hiding in Java which is an important concept in object-oriented programming. We will cover So let’s get started. What is Data Hiding in

Why Aren’t You Getting Interview Calls? 📞❌

It might just be your resume. Let us pinpoint the problem for free and supercharge your job search. 

Newsletter

Don’t miss out! Subscribe now

Log In