Q:

Java program to implement interface with hierarchical inheritance

belongs to collection: Java Interface Programs

0

Java program to implement interface with 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 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.

 

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

total answers (1)

Create an interface Animal with methods - animalSo... >>
<< Java program to implement multiple-inheritance usi...