Pages

Tuesday 22 October 2013

Dynamic Polymorphism

Poly means Many and Morphism means forms, and if this happens at run time, is called Dynamic Polymorphism.

Let's observe the following code

class Person{
  public void joiningDate(){
    System.out.println(" Person's Joining Date");
  }    
}

class Student extends Person{
  public void joiningDate(){
        System.out.println(" Student's Joining Date");
  }    
}

class Employee extends Person{
  public void joiningDate(){
         System.out.println(" Employee's Joining Date");
  }    
}



public class MainClass{
public static void mian(String args[]){
    Person p = new person();
    p.joiningDate();

    Student s =  new Student();
    p = s;
    p.joiningDate();

    Employee e  = new Employee();
    p = e;
    p.joiningDate();
  }
}


output:-
     Person's Joining Date
     Student's Joining Date
     Employee's Joining Date


Explanation: - In the above code Person is super class and both Student and Employees classes are childs of Person class. The method joiningDate() is overridden in both children classes.

 Student s =  new Student();  // Created an object of type Student
    p = s;                             // Assigned the child's object to parent
    p.joiningDate();               // invoking the child's function.

At runtime p references to the Student , so overridden joiningDate() method in Student class is class invoked. Similarly overridden joiningDate() method in Employee class is class invoked for 
    Employee e  = new Employee();
    p = e;
    e.joiningDate();

In all the three cases we are calling  p.joiningDate(); same method, But which joiningDate() method is to be called is decided at runtime dynamically (depends on address of the subclass?). This is called Dynamic Binding or Dynamic Polymorphism.

Dynamic Polymorphism is achieved through method Overriding.
Static Polymorphism is achieved through method Overloading.



No comments:

Post a Comment