What is polymorphism?
It is the ability to substitute one type in place of another.
- This allows us to write code in a generic way. We can write our code against an expected contract without worrying about all the details of an implementation. For e.g. you can write some code against a generic Vehicle type, and others can use it with more specific types (e.g. Car)
- It provides more flexibility and reduces code repetition to support similar behavior of different objects.
- It allows us to modularize our code better. We can program against a type without having to have a source code dependency on concrete types. This in turn allows the concrete types to be developed independently.
How is Polymorphism achieved?
- Using interfaces in languages that support it — where you can program against an interface and at runtime other concrete types can be used in it’s place.
- This can be used using inheritance where you can program against a parent type, and at runtime you can pass in other concrete sub types.
- Duck typing in languages with a dynamic type system. You can pass any object that contains the expected methods at runtime and the program will use that. This is similar to using interfaces for Polymorphism, except the language does it automatically.
- Method overloading is another form of Polymorphism. You can offer the same interface to the consumer of a class, but support different types of input objects.
- Java generics offer a form of Polymorphism where data structures and algorithms can be written in a generic way to support various types
What is static vs. dynamic Polymorphism?
- Dynamic Polymorphism occurs at runtime where the concrete behavior to use is determined at runtime. An example of this is: invoking a method on an interface in Java, at compile time, the compiler just makes sure the types are compatible. But linking the behavior to execute happens at runtime; the runtime looks at the concrete type it receives and links the interface method call to the corresponding method call in the concrete type
- Static Polymorphism occurs at compile time where the concrete behavior to use is determined at compile time. An example of this is method overloading in Java; the compiler knows which variant of a method to invoke at compile time