Monday, April 4, 2016

Java OOP - Polymorphism


When I was a kid, I used to watch "Mighty Morphin Power Ranger" on TV, best TV show ever!!! I always wanted to be the Red Ranger!! (but please don't tell my secret lol). Well the point here is that this group of teenager had the ability to "morph" into super-powered warrior. In Java we have something similar and it is called "Polymorphism ".

Polymorphism is in programming, the ability OR capability of a method to behave and do different stuff based on the object that is acting upon.

In Java, Polymorphism has two types:

  • Method Overloading - Compile time polymorphism (static binding) &
  • Method Overriding - Runtime polymorphism (dynamic binding) 

Method Overloading: there are several methods present in a class having the same but different types/order/number of parameters. In this case, Java knows which method needs to invoke by checking the method signatures. 

class DisplayOverloading
{
    public void disp(char c)
    {
         System.out.println(c);
    }
    public void disp(char c, int num)  
    {
         System.out.println(c + " "+num);
    }
}

class Sample
{
   public static void main(String args[])
   {
       DisplayOverloading obj = new DisplayOverloading();
       obj.disp('a');
       obj.disp('a',10);
   }
}

Output:

a
a 10


Method Overriding: If subclass (child class) has the SAME method as declared in the parent class, it is know as method overriding. That is to say, if child class provides the specific implementation of the method that has been provided by one of its parent class, well, this is know as method overriding.

Rules for method overriding:
  • must be IS-A relationship (inheritance)
  • method MUST have same name as in the parent class
  • method MUST have same parameter as in the parent class
  • the access level cannot be more restrictive than the overridden method's access level
  • method declared final cannot be overridden
  • constructors cannot be overridden

class Animal{

   public void move(){
      System.out.println("Animals can move");
   }
}

class Dog extends Animal{

   public void move(){
      System.out.println("Dogs can walk and run");
   }
}

public class TestDog{

   public static void main(String args[]){
      Animal a = new Animal(); // Animal reference and object
      Animal b = new Dog(); // Animal reference but Dog object

      a.move();// runs the method in Animal class

      b.move();//Runs the method in Dog class
   }
}

Output:

Animals can move
Dogs can walk and run











No comments:

Post a Comment