how2examples.com
Home - Introduction to Java Programming

Java Interfaces

Java supports a special kind of construct called an interface. An interface can define any number of abstract methods but, unlike abstract classes, an interface cannot define any non-abstract methods. Like abstract classes, interfaces are not instantiated directly. Classes implement an interface using the implements keyword. A non-abstract class implementing an interface has to provide an implementation of all the methods the interface defines. Although Java does not support multiple class inheritance (i.e. a class can only directly extend one other class) a class can implement any number of interfaces.

All methods defined in an interface are abstract and public (it is not required to explicitly use the public and abstract keywords). All variables defined in an interface are public, final and static (it is not required to explicitly use the public, static and final keywords).

Contents of InterfaceExample.java:
public class InterfaceExample {
   public static void main(String[] args) {
      System.out.print(X.X_VAR);
      System.out.print(Y.Y_VAR);
      A a = new A();
      B b = new B();
      processX(a);
      processX(b);
      processY(a);
   }
   
   static void processX(X x) {
      x.x();
   }
   
   static void processY(Y y) {
      y.y();
   }
}

interface X {
   String X_VAR = "X.X_VAR ";
   void x();
}

interface Y {
   public static final String Y_VAR = "Y.Y_VAR ";
   public abstract void y();
}

class A implements X, Y {
   @Override
   public void x() {
      System.out.print("A.x() ");
   }

   @Override
   public void y() {
      System.out.print("A.y() ");
   }
}

class B implements X {
   @Override
   public void x() {
      System.out.print("B.x() ");
   }
}
Command to compile InterfaceExample.java:
javac InterfaceExample.java
Command to run InterfaceExample:
java InterfaceExample
Output from running InterfaceExample:
X.X_VAR Y.Y_VAR A.x() B.x() A.y()