In JavaScript, we don’t have a built-in interface concept like in some other languages. However, we can simulate interfaces using classes and inheritance. In this example, we define a base Geometry class that acts as our interface.
The Rect and Circle classes extend the Geometry class and implement the area() and perim() methods. This is equivalent to implementing an interface in languages with explicit interface support.
The measure function demonstrates polymorphism by accepting any object that adheres to the Geometry interface (i.e., has area() and perim() methods).
In the main function, we create instances of Rect and Circle and pass them to the measure function, showing how we can use these objects interchangeably where a Geometry is expected.
To run this program, you would save it to a file (e.g., geometry.js) and execute it with Node.js:
This example demonstrates how to implement interface-like behavior in JavaScript using classes and inheritance, providing a similar structure to the original example while using JavaScript’s object-oriented features.