Java Tutorial
🔍
Java ProgramsOOPInterfaces & Polymorphism

Interfaces & Polymorphism in Java

intermediate·  OOP  ·  Interfaces

Problem

An interface defines a contract of methods that any implementing class must provide, each in its own way.

Create a Shape interface implemented by both a Circle and a Rectangle class.

Java Program

Java
interface Shape { double area(); // no implementation — each class must supply its own } class Circle implements Shape { double radius; Circle(double radius) { this.radius = radius; } public double area() { return Math.PI * radius * radius; } } class Rectangle implements Shape { double w, h; Rectangle(double w, double h) { this.w = w; this.h = h; } public double area() { return w * h; } } public class ShapeDemo { public static void main(String[] args) { // Different concrete classes, stored through their shared interface type Shape[] shapes = { new Circle(3), new Rectangle(4, 5) }; for (Shape s : shapes) { // Same call, different implementation depending on the actual object System.out.printf("Area: %.2f%n", s.area()); } } }

Output

Area: 28.27 Area: 20.00

Core Logic

Two unrelated classes implement the same interface here, and calling the same method through it produces different behavior depending on the object.

How It Works
  1. 1interface Shape declares an area() method with no implementation.
  2. 2Circle and Rectangle each implements Shape and supply their own formula for area().
  3. 3Both objects are stored in a single Shape[] array, even though they're different concrete classes.
  4. 4The loop calls s.area() on each element — the same method call, resolved to a different implementation depending on the object's actual class.
The same s.area() call prints 28.27 for the Circle and 20.00 for the Rectangle.
💡

Key Point: Programming against the Shape interface — instead of the concrete classes — is what lets new shapes be added later without touching this loop.

Key Concepts

interfaceimplementspolymorphism

Related Programs