Published by: Dikshya
Published date: 30 Jun 2023
To create and implement an interface, you'll need to follow a few steps. Here's a general outline of the process:
Define the Interface:
Declare the Interface:
interface
keyword.Implement the Interface:
Use the Interface:
// Step 1: Define the Interface
public interface Drawable {
void draw();
}
// Step 2: Declare the Interface
// Step 3: Implement the Interface
public class Circle implements Drawable {
@Override
public void draw() {
System.out.println("Drawing a circle");
}
}
public class Square implements Drawable {
@Override
public void draw() {
System.out.println("Drawing a square");
}
}
// Step 4: Use the Interface
public class Main {
public static void main(String[] args) {
Drawable circle = new Circle();
Drawable square = new Square();
circle.draw(); // Output: Drawing a circle
square.draw(); // Output: Drawing a square
}
}
In the example above, the Drawable
interface defines a single method draw()
. The Circle
and Square
classes implement the Drawable
interface by providing their own implementation of the draw()
method. The Main
class demonstrates how the interface can be used to create objects of different implementing classes and invoke the draw()
method on them.
Benefits of using interfaces: