Home > Java > javaTutorial > body text

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

WBOY
Release: 2023-08-19 23:45:07
forward
799 people have browsed it

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();
   }
}
Copy after login

Output

Main Interface Method
Sub Interface Method
Copy after login

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!

Related labels:
source:tutorialspoint.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template