Polymorphism

Learn about the polymorphism in object-oriented programming.

Polymorphism is a showy name describing a simple concept: different behaviors happen to depend on which subclass is being used, without having to explicitly know what the subclass actually is. It is also sometimes called the Liskov Substitution Principle, honoring Barbara Liskov’s contributions to object-oriented programming. We should be able to substitute any subclass for its superclass.

Example

As an example, imagine a program that plays audio files. A media player might need to load an AudioFile object and then play it. We can put a play() method on the object, which is responsible for decompressing or extracting the audio and routing it to the sound card and speakers. The act of playing an AudioFile could feasibly be as simple as:

audio_file.play()

However, the process of decompressing and extracting an audio file is very different for different types of files. While .wav files are stored uncompressed, .mp3, .wma, and .ogg files all utilize totally different compression algorithms.

Using polymorphism

We can use inheritance with polymorphism to simplify the design. Each type of file can be represented by a different subclass of AudioFile, for example, WavFile and MP3File. Each of these would have a play() method that would be implemented differently for each file to ensure that the correct extraction procedure is followed. The media player object would never need to know which subclass of AudioFile it is referring to; it just calls play() and polymorphically lets the object take care of the actual details of playing. Let’s look at a quick skeleton showing how this might work:

Get hands-on with 1200+ tech skills courses.