Polymorphism in Java in Details Step by Step

    1. Compile time Polymorphism (method overloading). 
    2. Runtime Polymorphism (method overriding).

    1. Compile time Polymorphism (method overloading). 


Overloading is compile time polymorphism where more than one methods share the same name with different parameters or signature.


Example:


class TestOverloading

{

    public void display(char c)

    {

         System.out.println(c);

    }

    public void display(char c, int num) 

    {

         System.out.println(c + " "+num);

    }

}

class TestMainClass

{

   public static void main(String args[])

   {

       TestOverloading obj = new TestOverloading ();

       obj. display('a');

       obj. display('a',10);

   }
         }

    2. Runtime Polymorphism (method overriding).


Overriding is run time polymorphism having same method with same   parameters   or signature, but associated in a class & its subclass.


Example:


class Eat{
   //Overridden method
   public void eat()
   {
      System.out.println("Eating");
   }
}
class Rice extends Eat {
   //Overriding method
   public void eat(){
      System.out.println("He is eating rice");
   }
   public static void main( String args[]) {
      Rice obj = new Rice ();
      //This will call the child class version of eat()
      obj.eat();
   }
                }
 

1 comment:

  1. Excellent Post. Are you looking for Laptops for your training? Click here Laptop Price to select your idle Laptop in budget.

    ReplyDelete