ADVERTISEMENT
ADVERTISEMENT

Java program to implement interface with hierarchical inheritance

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

Problem Solution:

In this program, we will implement hierarchical inheritance using the interface. Here, one superclass is inherited by two sub-classes.

Program/Source Code:

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

// Java program to demonstrate interface implementation 
// with hierarchical inheritance

interface MyInf {
  //Method Declaration
  void Method1();
}

class Sample1 implements MyInf {
  //Method definition
  public void Method1() {
    System.out.println("Method1() called");
  }
}

class Sample2 extends Sample1 {
  //Method definition
  public void Method2() {
    System.out.println("Method2() called");
  }
}

class Sample3 extends Sample1 {
  //Method definition
  public void Method3() {
    System.out.println("Method3() called");
  }
}

public class Main {
  public static void main(String[] args) {
    Sample2 S2 = new Sample2();
    Sample3 S3 = new Sample3();

    S2.Method1();
    S2.Method2();

    S3.Method1();
    S3.Method3();
  }
}

Output:

Method1() called
Method2() called
Method1() called
Method3() called

Explanation:

In the above program, we created an interface MyInf that contains the abstract Method1(). Then we implemented the interface in the Sample1 class. After that Sample1 class is inherited by Sample2 and Sample3 classes. The Sample2 and Sample3 classes also contain extra methods.

The Main class contains a method main(). The main() method is the entry point for the program, here we created the objects of the Sample2 and Sample3 classes. After that, we called methods and printed the result.

Java Interface 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.