In Java, an interface is a type that defines a set of methods that a class must implement. An interface is a way to specify a contract that a class must follow, without providing any implementation for the methods.
To define an interface in Java, you use the interface
keyword, followed by the interface name and the list of methods. Here is an example of how to define an interface in Java:
public interface MyInterface { void method1(); int method2(String s); }
This code defines an interface called MyInterface
that has two methods: method1
and method2
. The method1
method does not have any parameters and does not return a value, while the method2
method takes a single String
parameter and returns an int
value.
To implement an interface in a class, you use the implements
keyword in the class declaration, followed by the interface name. Here is an example of how to implement the MyInterface
interface in a class:
public class MyClass implements MyInterface { @Override public void method1() { // Implement the method1 method } @Override public int method2(String s) { // Implement the method2 method return 0; } }
This code defines a class called MyClass
that implements the MyInterface
interface. The MyClass
class must implement all the methods defined in the MyInterface
interface, as indicated by the @Override
annotations. If the class does not implement all the methods, it will not compile.
Interfaces are useful in Java because they allow you to define a set of methods that a class must implement, without having to specify the implementation details. This enables you to create flexible and reusable code, as well as to decouple the implementation of a class from its interface.