You can create a reference to an interface in Java by declaring a variable with the interface's type.
Here's a simple example:
interface Drawable {
void draw();
}
class Circle implements Drawable {
@Override
public void draw() {
System.out.println("Drawing a circle.");
}
}
public class Main {
public static void main(String[] args) {
// Create a reference to the Drawable interface
Drawable circle = new Circle();
// Call the draw() method using the interface reference
circle.draw();
}
}
In this example:
Drawable
is an interface defining adraw()
method.Circle
is a class implementing theDrawable
interface.- We create a variable named
circle
of typeDrawable
and assign a newCircle
object to it. - We can then call the
draw()
method using thecircle
reference.
This demonstrates that you can hold an object of a class implementing an interface in a variable of the interface type.
This concept is crucial for polymorphism in Java. It allows you to write code that works with any object implementing a particular interface, regardless of its specific class.