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++)
{
    animals[i].eat();


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}
or
public Animal getPet(String sound)
{
   if(sound.equals("bark"))
    {
         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.

4 comments:

  1. Hi, I am confused here. You said "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." I am guessing when an object is created using new it must be heap. You have mentioned that it will be stack in your 1st statement and heap in the next. Which is the correct one?

    ReplyDelete
    Replies
    1. So the reference is on the stack but the actual object (where memory is allocated) is on the heap.

      So

      Object obj1 = new Object();

      here obj1 will be on stack and the actual object created will be on heap. Now if you say

      Object obj2 = obj1;

      this essentially means obj2 reference will also start pointing to same object obj1 was pointing. So both obj1 and obj2 are on stack but the actual object is on the heap and both references point to the same object.

      Also you must know about garbage collection in java - when all references to an object are null that object is eligible for GC which essentially means when obj1 and obj2 become null (references in stack become null) the actual object on heap is eligible for GC.

      Hope this clarifies your doubt.

      Delete
    2. Thank you :) It clarified my doubt. I have another question. In the example you have mentioned:
      animals[0] = new Dog();
      animals[0] = new Cat();
      animals[0] = new Lion();
      animals[0] = new Tiger();
      animals[0] = new Wolf();
      Does the index of animals remains 0. I hoped it would be 0,1,2,3,4 respectively. Since we are defining animals as array.

      Delete
    3. Yeah you are right. Idea is to understand that single superclass reference can refer to multiple subclasses. Have edited the post. Thanks :)

      Delete

t> UA-39527780-1 back to top