Concept · Core

Polymorphism

One call, many forms: the SAME method name resolves to different behaviour depending on the actual object — decided at runtime.

Asked atAmazonMicrosoftAdobe
step 1 / 11
1/2One interface, many implementations
«interface»
Shape
+ area(): double
Circle
- r: double
+ area()
Square
- s: double
+ area()
Triangle
- b, h
+ area()
One interface, many implementations
1interface Shape { double area(); }
2 
3class Circle implements Shape { double area(){ return PI*r*r; } }
4class Square implements Shape { double area(){ return s*s; } }
5class Triangle implements Shape { double area(){ return b*h/2; } }
State
contractarea(): double

A supertype declares the contract: every Shape promises an area() method — but says nothing about HOW.