Q:

Java program to implement hierarchical inheritance

belongs to collection: Java Inheritance Programs

0

Java program to implement hierarchical inheritance

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

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.

Program/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();

    obj1.BaseMethod();
    obj1.Derived1Method();

    obj2.BaseMethod();
    obj2.Derived2Method();
  }
}

Output:

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

Explanation:

In the above program, we created 4 classes BaseDerived1Derived2, 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 Derived1Derived2 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 Derived1Derived2 classes and called the method of Base class using both objects and printed the result.

 

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

Java program to call a superclass constructor from... >>
<< Java program to implement multi-level inheritance...