Skip to main content

ProwessApps

Learn · Practice · Excel

Java Program to demonstrate the use of Interface.

Java Code Example — Abstract and Interface Programs

ADVERTISEMENT

Java Program to demonstrate the use of Interface.

Objective

Write a Java program to demonstrate the basic use of an Interface.

Algorithm / Approach

  1. Define an interface named Shape with a single method signature void draw();.
  2. Create a class Rectangle that implements Shape and provides the body for the draw() method.
  3. Create a class Circle that implements Shape and provides its own body for draw().
  4. In the main method, use an Interface reference (Shape s = new Rectangle();) to call the methods.
Rectangle.java
interface Shape {
 void draw();
}
class Rectangle implements Shape {
 public void draw() {
  System.out.println("Draw Rectangle");
 }
}
class Circle implements Shape {
 public void draw() {
  System.out.println("Draw Circle ");
 }
}
class Test {
 public static void main(String[] a)
 {
 Shape s = new Rectangle();
 s.draw(); 
 Shape s2 = new Circle();
 s2.draw();
 }
}

Expected Output

Draw Rectangle
Draw Circle

Explanation of the Program

  • An Interface in Java is a blueprint of a class. Unlike abstract classes, which can have some concrete methods, an interface (prior to Java 8) can ONLY contain abstract methods and final variables.
  • Interfaces represent a strict contract. If a class claims to implement Shape, it is legally bound by the compiler to provide the code for every method defined in that interface.
  • Notice that we use the keyword implements instead of extends when connecting a class to an interface.

Complexity

Time Complexity O(1)
Space Complexity O(1)
ADVERTISEMENT