A2oz

How to Create a Reference of an Interface in Java?

Published in Java Programming 2 mins read

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 a draw() method.
  • Circle is a class implementing the Drawable interface.
  • We create a variable named circle of type Drawable and assign a new Circle object to it.
  • We can then call the draw() method using the circle 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.

Related Articles