Overview: What is Polymorphism

Polymorphism is a word that can actually be traced back to biology, not programming! It's a principle where an organism can have several different forms. This biological principle can also be applied to OOP and Java, too!

When we break down the word polymorphism, it can be split into "poly", which means many, and "morphism", which menas form. It simply means many forms. In Java, it means that the methods that get called when the code is run depend on the type of the object at run-time.

For example, the variable hi declared below as a declared type of Object, but a run-time type of String. If we use a String method, such as hi.indexOf(), this causes a compiler error as the type is String only at the run-time.

Object hi = new String("hi"); 
Since the type at compile time is Object, the indexOf() method doesn't exist in that class or any parent class of it.

Method Overriding

Method overriding is when a subclass has a method with the same name as one in the subclass, and is usually done to provide a specific implementation of a method already provided by the subcloass. It ia used for runtime polymorphism, as at the runtime the Java Virtual Machine decides to use the subclass' method instead of the superclass'.

As we can see above, the makeSound() method is overriden in the Cat and Dog subclasses of Animal, as they make different sounds. This is a simple example of overriding methods.