Interface in Java

Profile picture for user arilio666

In Java, an interface is a set of abstract methods and constants. It's comparable to a class in that it defines a set of methods but doesn't implement them. Instead, classes that implement the interface supply the implementation of the methods.

In Java, you use the interface keyword followed by the interface's name to declare it. As an example:

public interface MyInterface {
   public void method1();
   public void method2();
}
  • This specifies the interface MyInterface, which has two abstract methods, method1() and method2(). Any class that implements this interface is required to implement these methods.

Use the keyword implements followed by the interface name to implement an interface in a class. As an example:

public class MyClass implements MyInterface {
   public void method1() {
       // implementation of method1
   }
   public void method2() {
       // implementation of method2
   }
}
  • This declares the MyClass class, which implements the MyInterface interface. It includes implementations for the methods method1() and method2().

Constants can also be defined in interfaces using the final keyword. As an example:

public interface MyInterface {
   public static final int MY_CONSTANT = 100;
}
  • This creates a constant named MY_CONSTANT with the value 100. Constants in interfaces are implicitly public, static, and final. Therefore such modifiers are not required to be specified explicitly.

Conclusion:

To summarise, interfaces in Java describe a set of methods that classes can implement but do not offer implementation for those methods. Constants can also be found in interfaces.