An interface in Java is a type that defines a set of abstract methods that a class can implement. An interface can be thought of as a contract or a set of rules that a class must follow if it implements that interface. In addition to abstract methods, an interface can also contain constants and default methods.
To implement an interface in Java, a class must use the implements
keyword and provide implementations for all the abstract methods defined in the interface. A class can implement multiple interfaces, but can only inherit from a single superclass.
Here’s an example of an interface in Java:
public interface Drawable {
void draw();
}
public class Circle implements Drawable {
private int x;
private int y;
private int radius;
public Circle(int x, int y, int radius) {
this.x = x;
this.y = y;
this.radius = radius;
}
public void draw() {
System.out.println("Drawing a circle at (" + x + ", " + y + ") with radius " + radius);
}
}
In this example, the Drawable
interface defines a single method called draw()
. The Circle
class implements the Drawable
interface by providing its own implementation of the draw()
method. When you call the draw()
method on a Circle
object, Java will call the version of the method that is defined in the Circle
class.
Interfaces are useful when you want to define a common set of methods that a group of classes can implement, without specifying how those methods should be implemented. By defining the interface, you can ensure that all the implementing classes provide the necessary functionality, and you can use the interface as a type to manipulate objects of different classes that implement the same interface.