Interfaces with Multiple Implementations in Java


Write a Java program to demonstrate the use of interfaces with multiple implementations

  • The Shape interface declares an abstract method draw(), which represents the action of drawing a shape.
  • The Circle class implements the Shape interface and provides an implementation for the draw() method to draw a circle.
  • The Square class also implements the Shape interface and provides an implementation for the draw() method to draw a square.
  • In the Main class, objects of type Shape are created using polymorphism. Specifically, circle is assigned an instance of Circle, and square is assigned an instance of Square.
  • By calling the draw() method on these Shape objects, the appropriate draw() method implementation for each shape (circle or square) is invoked based on the actual runtime type of the object.
  • Therefore, when circle.draw() is called, it prints "Drawing a circle", and when square.draw() is called, it prints "Drawing a square".

Source Code

interface Shape
{
	void draw();
}
 
class Circle implements Shape
{
	@Override
	public void draw()
	{
		System.out.println("Drawing a circle");
	}
}
 
class Square implements Shape
{
	@Override
	public void draw()
	{
		System.out.println("Drawing a square");
	}
}
 
public class Main
{
	public static void main(String[] args)
	{
		Shape circle = new Circle();
		Shape square = new Square();
		circle.draw();
		square.draw();
	}
}

Output

Drawing a circle
Drawing a square

Example Programs