Java Programs

Java Practice

Java program to implement hierarchical inheritance

Learn how to implement hierarchical inheritance in Java?
Submitted by Nidhi, on March 23, 2022

Problem statement

In this program, we will implement hierarchical inheritance, here we will create a base class with a method and then inherit the created base class into 2 derived classes using the "extends" keyword.  Then we can access the base class method using objects of both derived classes.

Source Code

The source code to implement hierarchical inheritance is given below. The given program is compiled and executed successfully.

// Java program to implement hierarchical 
// inheritance

class Base {
  void BaseMethod() {
    System.out.println("Base method called.");

class Derived1 extends Base {
  void Derived1Method() {
    System.out.println("Derived1 method called.");

class Derived2 extends Base {
  void Derived2Method() {
    System.out.println("Derived2 method called.");

public class Main {
  public static void main(String[] args) {
    Derived1 obj1 = new Derived1();
    Derived2 obj2 = new Derived2();




Base method called.
Derived1 method called.
Base method called.
Derived2 method called.


In the above program, we created 4 classes Base, Derived1, Derived2, and Main. The Base class contains a method BaseMethod(), The Derived1 class contains a method Derived1Method(), The Derived2 class contains a method Derived2Method(). Here, we inherited the Base class into Derived1, Derived2 classes using the "extends" keyword to implement hierarchical inheritance.

The Main class contains a method main(). The main() method is the entry point for the program, here we created the objects of Derived1, Derived2 classes and called the method of Base class using both objects and printed the result.

Java Inheritance Programs »

Comments and Discussions!

Load comments ↻

Copyright © 2024 www.includehelp.com. All rights reserved.