What is Polymorphism ?

Photo by Kyle Glenn on Unsplash

What is Polymorphism ?

Polymorphism is one of the core concepts in OOP languages and describes the concept that you can use different classes with the same interface.

Polymorphism means "many forms", and it occurs when we have many classes that are related to each other by inheritance.

Java supports 2 types of polymorphism:

  • static or compile-time

  • dynamic or run-time

Static polymorphism

Like many other OOP languages, allows you to implement multiple methods within the same class that use the same name. But, Java uses a different set of parameters called method overloading and represents a static form of polymorphism.

Dynamic polymorphism

It is also known as runtime polymorphism. It is a process in which a function call to the overridden method is resolved at Runtime. This type of polymorphism is achieved by Method Overriding.

Advantages of Polymorphism in Java:

  1. Increases code reusability by allowing objects of different classes to be treated as objects of a common class.

  2. Improves readability and maintainability of code by reducing the amount of code that needs to be written and maintained.

  3. Supports dynamic binding, enabling the correct method to be called at runtime, based on the actual class of the object.

  4. Enables objects to be treated as a single type, making it easier to write generic code that can handle objects of different types.

Disadvantages of Polymorphism in Java:

  1. It can make it more difficult to understand the behaviour of an object, especially if the code is complex.

  2. This may lead to performance issues, as polymorphic behaviour may require additional computations at runtime.

Summary

Polymorphism is one of the core concepts in OOP languages and describes the concept wherein you can use different classes with the same interface. Each of these classes can provide its implementation of the interface.

Java supports two kinds of polymorphism. You can overload a method with different sets of parameters. This is called static polymorphism because the compiler statically binds the method call to a specific method.

Within an inheritance hierarchy, a subclass can override a method of its superclass. If you instantiate the subclass, the JVM will always call the overridden method, even if you cast the subclass to its superclass. That is called dynamic polymorphism.