Thursday, 18 April 2013

Polymorphism in Java

Before we begin learning what is polymorphism and how is it useful let us step back and see how references and objects are created in Java.

Consider following line of Code

Dog myDog = new Dog();

It may look like a simple instance creation but includes multiple statements.
So when we say Dog myDog = new Dog() what actually happens is as follows - myDog is a reference(or you can visualize it as a pointer) which can refer to an object of type Dog. Note this reference is on the stack and not on the heap. When we use the new operator object is allocated memory on the heap and the reference points to this object. This is when we say object is created.

Important point to note here is that the reference type and the object type are the same i.e both are of type Dog.

But with polymorphism reference type and the object type can be different!!

All of polymorphism can be stated in a single line. Do keep this statement in mind -
"Super class reference for subclass object"

This means reference type mentioned above can be any super class of the subclass object to which it is pointing.

So if we have Class Dog extends Animal which means Animal is the super class of Dog then we can say
Animal myDog = new Dog(); 

To explain this further let us take an example -
Lets say we have an array of type Animal 

Animal[] animals = new Animal[5];

This means we have 5 references of type Animal
Now if Dog,Cat,Lion,Tiger,Wolf are subclasses of Animal then we can say -

animals[0] = new Dog(); 
animals[1] = new Cat();  
animals[2] = new Lion(); 
animals[3] = new Tiger(); 
animals[4] = new Wolf(); 

So we have multiple object references in the same array. Realizing the usefulness of polymorphism yet? Well there is more to come.
Now lets say we do something like -

for(int i=0; i< animals.length; i++)

What happens now?At runtime JVM will figure out that animals[i] say animals[0] refers to object of type Dog and call the .eat() function in Dog class. But there is a catch .eat() function must be defined in Animal class.  You must define a function in the super class and then you may override it in sub class according to your implementation.

You can use polymorphism in passing arguments in a function as well as while returning values.
Example -

public void feedAnimal(Animal animal){//implementation}
public Animal getPet(String sound)
         Dog myDog = new Dog();
         return  myDog;
    // more code 

I hope you get the point of polymorphism by now. You need not create separate function getPet() for each type of Animal or you need not create feedAnimal() function for each type of Animal.

Polymorphism will be used in a lot of codes without mentioning. We will refer to this post whenever possible but keep this concept in mind.

t> UA-39527780-1 back to top