+92 332 4229 857 99ProjectIdeas@Gmail.com

Polymorphism (Java)


Polymorphism (Java)
Polymorphic” literally means “of multiple shapes” and in the context of OOP, polymorphic means “having multiple behavior.
A polymorphic method results in different actions depending on the object are referenced, also known as late binding or run-time binding.

For example 
public class Employee {
       private int id;
       private String name;
         //parameterized constructor
         public Employee(int id, String name){
             this.id = id;
             this.name = name;
         }

         //default constructor
         public Employee(){
                id = 10;
                name = "not set";
         }
         public void display(){
                System.out.println("Employee id:" + id + " name:" + name);
      }
}

public class Teacher extends Employee {//here Teacher extending(inheriting) the Employee class

   private String qualification;

   //default constructor
   public Teacher () {
        //implicit call to superclass default constructor          
        qualification = "";     
   }

   //parameterized constructor
   public Teacher(int id, String name, String qual){
      super(id,name); //call to superclass(Employee) constructor must be in first line       
      qualification = qual;
   }
  
   public void display(){//same name method but here is polymorphic in nature
        super.display(); //call to superclass(Employee) display method
        System.out.println("Qualifications :" + qualification);
   }
}

public class Test {

  public static void main(String[] args) {
  //creating Employee class references
 Employee reference1 , reference2;
        reference1 = new Employee(18, "Maverick");
        reference1.display();//call to Employee display method
            
 //Employee object can hold Teacher class object because it is a child class
        reference2 = new Teacher(13,"Tom Cruise","Actor");
        reference2.display();//call to Teacher display method

 //But if you hold the Employee object to Teacher it would give you ClassCastException
Teacher teacher;
       teacher = (Teacher)new Employee(34, "Maryam");//Casting To Teacher
teacher.display();

}
}

0 comments: