Java Program to demonstrate the use of Interface.
Objective
Write a Java program to demonstrate the basic use of an Interface.
Algorithm / Approach
- Define an interface named
Shapewith a single method signaturevoid draw();. - Create a class
Rectanglethatimplements Shapeand provides the body for thedraw()method. - Create a class
Circlethatimplements Shapeand provides its own body fordraw(). - 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
implementsinstead ofextendswhen connecting a class to an interface.
Complexity
Time Complexity
O(1)
Space Complexity
O(1)