In Java, an interface is a collection of abstract methods and constants that can be implemented by any class. An interface provides a way to define a set of behaviors that a class must implement. The class that implements the interface provides concrete implementations of the abstract methods defined in the interface. Here’s an example of an interface:
public interface Drawable {
void draw();
double getArea();
}
In this example, the Drawable interface defines two abstract methods: draw and getArea. Any class that implements the Drawable interface must provide concrete implementations of these methods.
To implement an interface, a class must use the implements keyword followed by the name of the interface. Here’s an example of a class that implements the Drawable interface:
public class Circle implements Drawable {
private double radius;
public Circle(double radius) {
this.radius = radius;
}
public void draw() {
System.out.println("Drawing a circle with radius " + radius);
}
public double getArea() {
return Math.PI * radius * radius;
}
}
In this example, the Circle class implements the Drawable interface by providing concrete implementations of the draw and getArea methods. When you create an object of the Circle class, you can call the draw and getArea methods just as you would with any other object that implements the Drawable interface.
One of the key benefits of interfaces is that they allow for polymorphism. Since any class that implements an interface can be treated as an instance of that interface, you can write methods that can accept any object that implements the interface, regardless of its specific class. Here’s an example:
public static void drawShape(Drawable shape) {
shape.draw();
}
In this example, the drawShape method takes an object that implements the Drawable interface as a parameter. This method can be called with any object that implements the Drawable interface, such as a Circle object or a Rectangle object.
Interfaces are a powerful tool in Java that allow you to define a set of behaviors that any class can implement. By using interfaces, you can write more flexible and reusable code that can work with a wide variety of objects.