Contents:

Where to start your IT career? Get a detailed guide in our Telegram channel for free! Click on the banner and join the channel – you'll find the guide pinned.
Learn MoreIf you're just starting to learn object-oriented programming, you're probably familiar with four core concepts: abstraction, encapsulation, inheritance, and polymorphism. The first three concepts were covered in previous articles. In this article, we'll focus on polymorphism: we'll explore its essence, how it works, and its practical implications for developers. Polymorphism allows objects of different classes to process data using a single interface, which simplifies code and increases its flexibility. Understanding polymorphism is key to effectively using object-oriented programming, as it contributes to the creation of more versatile and scalable solutions.
Before we begin, it's important to note that many aspects of this article will be difficult to understand without a basic knowledge of the fundamentals and principles of object-oriented programming (OOP). If you'd like to refresh your knowledge in this area, we recommend studying our in-depth material. This will help you better absorb the information and deepen your understanding of the topics that will be discussed in the article.
- What are classes and objects?
- Features of working with objects.
- Access modifiers, encapsulation.
- Polymorphism and method overloading.
- Polymorphism.
- Inheritance and a little more polymorphism.
- Abstract classes and interfaces.
- Practical work.
What is polymorphism?
Object-oriented programming (OOP) is based on the concept of objects, which are the basic units of software development. Even objects with different appearance and functionality can have the same interface, which allows them to implement common methods in their own way. For example, the "quadcopter" and "airplane" objects might each have a "fly" method, but each will implement it with its own unique characteristics and operating principles. This property of OOP promotes a more flexible and structured approach to program development, facilitating the process of extending and modifying code.
Polymorphism allows the same methods to be applied to objects of different classes. Regardless of the internal structure of these objects, in object-oriented programming, you can issue the same command, "Fly," to both an airplane and a quadcopter. Each will execute this command differently: the quadcopter will begin rotating its blades, and the airplane will accelerate down the runway. Polymorphism thus ensures flexibility and code reuse, which is an important aspect of effective programming.
Polymorphism can be compared to an air traffic controller at an airport. He doesn't care what fuel system the airplane has or how the afterburner functions. His task is simply to issue the command, "Clear for takeoff." After that, the internal processes on board the airplane are launched, over which the air traffic controller no longer has any influence. Polymorphism in programming works similarly, allowing objects of different types to respond to the same commands, providing flexibility and extensibility in code.
Polymorphism is a concept that translates from Greek as "many-formed." It implies that the same method can be implemented in different ways. An example of polymorphism is the difference in the flight of a drone and an airplane. Both devices perform air transport functions, but do so using different approaches and technologies. Polymorphism plays an important role in programming, allowing the creation of flexible and extensible systems that can adapt to different conditions and requirements.
How Polymorphism Looks in Code
When creating an online store for merchandise for a well-known YouTube channel, it is necessary to provide functionality that allows customers to add products to their cart. In our case, we offer three types of products: T-shirts, mugs, and notebooks. To implement this task, we will need integration with a content management system and the use of JavaScript to handle events when products are added to cart.
When adding a product, it's important to display a message to the user confirming the successful completion of the action. You can do this by using a pop-up notification or updating an element on the page with the text "Product added to cart." This will improve the user experience and allow shoppers to be confident that their choice has been taken into account.
Also, it's worth considering SEO optimization of product pages. Make sure each product has unique titles, meta descriptions, and keywords related to your brand and product types. This will help increase the visibility of your online store in search engines and attract a larger target audience.
It's also important to regularly update the content, adding new products and special offers, which will help increase customer interest and improve search rankings.
There are two approaches to implementing the "add to cart" method. The first option is to create a separate method for each product category. This method is time-consuming and leads to sloppy code. The second option is to develop a single polymorphic method that will be universal for all objects. This approach is more efficient and optimal for our case. Let's look at the implementation process step by step.
A base class provides a framework for describing common properties of objects. In our example, this includes the product name and the ability to add it to cart. These properties ensure consistency and simplify product management in the system. A properly implemented base class allows for easy extension of functionality and the addition of new properties, which in turn improves the user experience and streamlines the shopping process.
While this may seem rather abstract now, it will become clearer later.
Derived classes extend the functionality of the base class by adding additional parameters. In this context, this means defining product characteristics, such as the size of a T-shirt, the volume of a mug, and the number of pages in a notebook. Such refinements allow for more accurate product descriptions and improved presentation in online stores.
A user visits our online store and selects three products: a size 48 "Acid" T-shirt, a 250ml "Omut" mug, and a 180-page "Tree of Life" notebook. He checks each product and clicks the "Add to Cart" button. At this point, the request is processed in the code. The system records the user's selection, adds the products to the virtual cart, and updates the available products. This is important to ensure that availability is displayed correctly and for further operations, such as placing an order. Every user action is recorded, which helps improve the user experience and optimize the shopping process.
We grouped the products into an array and used a loop to apply the AddToCart method to all the items at once. If our online store were real, the customer might see messages like the following:
We have achieved the planned result. You can check the full run of the program code and its functionality at this link.
Why Polymorphism Is Necessary
Polymorphism eliminates the need to create separate methods for each product type, such as AddToCartShirt for T-shirts or AddToCartCup for mugs. Instead, we can use a universal AddToCart method that works for all products. If new products, such as caps, are added to our store, we can simply make minor changes to the existing method to accommodate the new features, significantly simplifying code development and maintenance. Using polymorphism improves the readability and scalability of the application, making it easy to add new features and expand the store's functionality.
This is especially important for large commercial applications with complex logic. For example, if we consider not just an accessory store but a large marketplace like Ozon, then polymorphism becomes essential. Without it, the code can degenerate into an unstructured set of functions that perform the same tasks but have different names. This complicates project maintenance and development, reduces scalability, and increases the likelihood of errors. Polymorphism allows for a cleaner and more understandable architecture, making the code more flexible and easier to modify.
Polymorphism has three main advantages. First, it provides flexibility and extensibility of code, allowing the same interface to be used for different types of objects. Second, polymorphism simplifies software maintenance and modification, since changes to one class do not require significant rework in other parts of the code. Third, it improves code readability and structure, allowing developers to focus on a high level of abstraction. These advantages make polymorphism a key element in object-oriented programming.
- Readability. The less code and the better it is packaged, the easier it is for programmers to work and the faster development is.
- Scalability. You can add socks, pens, wristbands, pendants and a bunch of other different products to the store, and one command - AddToCart - will still be responsible for purchasing them.
- Code predictability. When we have one method for different objects, we feel calm. You don't have to worry about accidentally applying the "Add underwear to cart" command to socks and causing a program crash.
What's next
In object-oriented programming (OOP), polymorphism is most often associated with subtype polymorphism. This type of polymorphism allows objects of different classes to be called using a single method. However, there are also two other types of polymorphism: parametric and ad-hoc. In future articles, we will examine their differences and applicability in various programming scenarios in detail.
Reading is an important part of our lives, as it enriches knowledge, develops thinking, and opens new horizons. Books, articles, and blogs provide unique information and inspiration. Reading not only helps improve vocabulary but also contributes to a better understanding of the world around us. Regardless of the genre, every work we read leaves its mark and can change our perception of reality. Therefore, it is important to devote time to reading, choosing a variety of sources of information.
- What are objects and classes: Part 1 of the OOP guide
- Test: What do you know about Python creator Guido van Rossum?
- How to learn Python on your own and for free

