ADVERTISEMENT
ADVERTISEMENT

Java program to implement multi-level inheritance

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

Problem Solution:

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.

Program/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 »


ADVERTISEMENT
ADVERTISEMENT


Comments and Discussions!



ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT

Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.