Home  >  Article  >  Java  >  Why can't one interface implement another interface in Java?

Why can't one interface implement another interface in Java?

WBOY
WBOYforward
2023-08-19 23:45:07795browse

Why cant one interface implement another interface in Java?

In Java, an interface cannot implement another interface.

  • In Java, an interface is essentially a special type of class. Like classes, interfaces contain methods and variables. The difference is that interfaces are always completely abstract.
  • The definition of interface is similar to that of class, except that the keyword interface replaces class. The variables declared in the interface are static and final. The methods defined in the interface are public abstract methods.
  • An interface can extend any number of interfaces, but an interface cannot implement another interface, because if any interface is implemented, its methods must be defined, and An interface never has any methods defined.
  • If we try to implement an interface with another interface, a compile-time error will be thrown in Java.

Example

interface MainInterface {
   void mainMethod();
}
interface SubInterface extends MainInterface { // If we put <strong>implements </strong>keyword in place of <strong>extends,                                               </strong>// 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

The above is the detailed content of Why can't one interface implement another interface in Java?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:tutorialspoint.com. If there is any infringement, please contact admin@php.cn delete