DEV Community

Cover image for Understand Polymorphism once for all
Mateo Cerquetella
Mateo Cerquetella

Posted on

1 1

Understand Polymorphism once for all

The main reason for using interfaces is to achieve polymorphism and to provide developers with the ability to implement interface methods in their own way in the future.

In this example I will use TypeScript and I will put the repository at the end of the note

Suppose we have an interface and three classes:

Alt Text

This is the connector interface.

Now we are going to implement the Wifi communication.

Alt Text

Here we have developed our concrete class called WifiConnector which has its own implementation of type Connector.


Now we are creating our System which has a Connector component. This is called dependency injection.

Alt Text


Let's look at this line of code ...

Alt Text

Connector is an interface and must have the method doConnect().

Now, since Connector is an interface, the System class has much more flexibility.

We can pass any type that has implemented the Connector interface.
In the future, the developer will achieve more flexibility.


For example, now the developer wants to add a Bluetooth connection module:

Alt Text

We see that WifiConnector and BluetoothConnector have their own implementation.
There is a different way to connect.

So we can pass any of them to the System class as a constructor parameter. This is called polymorphism.

The System class is now not aware of whether it is Bluetooth or Wifi. We can even add another communication module such as Infrared, Bluetooth5 and whatever, simply by implementing the Connector interface.

This is called Duck Typing. The connector type is now dynamic since doConnect() is just a placeholder and the developer implements it as their own.

Here is the repository in case you need it and thanks for reading!

Image of Timescale

🚀 pgai Vectorizer: SQLAlchemy and LiteLLM Make Vector Search Simple

We built pgai Vectorizer to simplify embedding management for AI applications—without needing a separate database or complex infrastructure. Since launch, developers have created over 3,000 vectorizers on Timescale Cloud, with many more self-hosted.

Read more

Top comments (0)

Postgres on Neon - Get the Free Plan

No credit card required. The database you love, on a serverless platform designed to help you build faster.

Get Postgres on Neon

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay