Why an interface cannot implement another interface in Java?


An interface cannot implement another interface in Java.

  • An interface in Java is essentially a special kind of class. Like classes, the interface contains methods and variables. Unlike classes, interfaces are always completely abstract.

  • An interface is defined just like a class except for the keyword interface in place of a class, the variables are declared in an interface are static and final and the methods are defined in an interface are public abstract methods.

  • An interface can extend any number of interfaces but one interface cannot implement another interface, because if any interface is implemented then its methods must be defined and interface never has the definition of any method.

  • If we try to implement an interface with another interface, it will throw a compile-time error in Java.

Example

interface MainInterface {
   void mainMethod();
}
interface SubInterface extends MainInterface { // If we put implements keyword in place of extends,                                               // compiler throws an error.
   void subMethod();
}
class MainClass implements MainInterface {
   public void mainMethod() {
      System.out.println("Main Interface Method");
   }
   public void subMethod() {
      System.out.println("Sub Interface Method");
   }
}
public class Test {
   public static void main(String args[]) {
      MainClass main = new MainClass();
      main.mainMethod();
      main.subMethod();
   }
}

Output

Main Interface Method
Sub Interface Method

Updated on: 22-Nov-2023

9K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements