Home »
Java »
Java Programs
Java program to implement multi-level inheritance
Learn how to implement multi-level inheritance in Java?
Submitted by Nidhi, on March 23, 2022
Problem statement
In this program, we will implement multi-level inheritance, here we will create a base class with a method and then inherit the created base class into a derived class using the "extends" keyword. Then we will inherit the derived class into another class. After that, we can access all the inherited methods from the object of the low-level derived class.
Source Code
The source code to implement multi-level inheritance is given below. The given program is compiled and executed successfully.
// Java program to implement
// multi-level 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 Derived1 {
void Derived2Method() {
System.out.println("Derived2 method called.");
}
}
public class Main {
public static void main(String[] args) {
Derived2 obj = new Derived2();
obj.BaseMethod();
obj.Derived1Method();
obj.Derived2Method();
}
}
Output
Base method called.
Derived1 method called.
Derived2 method called.
Explanation
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 the Derived1 class and Derived1 into Derived2 using the "extends" keyword to implement multi-level inheritance.
The Main class contains a method main(). The main() method is the entry point for the program, here we created the object of the Derived2 class and called the methods of all classes, and printed the result.
Java Inheritance Programs »