Java Tutorial
🔍
What is OOP?Classes & ObjectsConstructorsAccess Modifiersthis Keywordstatic KeywordEncapsulationInheritancesuper KeywordMethod OverridingOverloading vs OverridingPolymorphismUpcasting & Downcastinginstanceof OperatorAbstractionAbstract ClassesInterfacesMarker InterfacesAbstract Class vs InterfaceObject ClasstoString() Methodequals() & hashCode()
Collections OverviewCollections HierarchyIterable InterfaceCollection InterfaceMap Interfaceequals() and hashCode()IteratorListIteratorFail-fast vs Fail-safe IteratorConcurrentModificationExceptionArrayListLinkedListHashSetLinkedHashSetTreeSetQueuePriorityQueueDequeArrayDequeHashMapLinkedHashMapTreeMapConcurrentHashMapCopyOnWriteArrayListList vs Set vs MapChoosing the Right CollectionComparableComparatorComparable vs ComparatorCollections Utility ClassArrays Utility ClassImmutable CollectionsCollection vs CollectionsVectorHashtableStackArrayList Internal WorkingLinkedList Internal WorkingHashMap Internal WorkingTreeMap Internal Working
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
interface Shapedeclares anarea()method with no implementation. - 2
CircleandRectangleeachimplements Shapeand supply their own formula forarea(). - 3Both objects are stored in a single
Shape[]array, even though they're different concrete classes. - 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