2016-07-18

Polymorphism in Java

Polymorphism (from the Greek meaning "having multiple forms")
Polymorphism means one thing in many form. an object to have more than one form. Polymorphism is capability of one object to behave in multiple ways.

There are following types of polymorphism :

Static polymorphism (compile time) function overloading :-
     Method Overloading is a feature that allows more than two methods having same name in a class with different parameters.

Example:

  1. public class Calculator{  
  2.   void add(int a,int b)
  3.   {
  4.   System.out.println(a+b);
  5.   }  
  6.   void add(int a,int b,int c)
  7.   {
  8.   System.out.println(a+b+c);
  9.   }  
  10.   
  11.   public static void main(String args[]){  
  12.   Calculator cal=new Calculator();  
  13.   cal.add(5,10,15);  
  14.   cal.add(5,10);  
  15.   }  
  16. }  




Dynamic polymorphism(runtime time) function overriding :-
     Methods with same name and with same signature in super class and sub class.

Example:

  1. public class Vehicle{
  2. void Name(){ 
  3. System.out.println("Vehicle")
  4. }
  5. }

  6. public class Car extends Vehicle{
  7. void Name(){ 
  8. System.out.println("Car")
  9. }
  10. }

  11. public class Bus extends Vehicle{
  12. void Name(){ 
  13. System.out.println("Bus")
  14. }
  15. }

  16. public class Test{
  17. public static void main(String args[]){
  18. Bus b=new Bus();
  19.     b.Name();
  20. Vehicle v= new Car();
  21.         b.Name(); 
  22. }
  23. }

4 comments:

  1. Polymorphism is the ability of an object to take on many forms. The most common use of polymorphism in OOP occurs when a parent class reference is used to refer to a child class object. Any Java object that can pass more than one IS-A test is considered to be polymorphic.Know more: Java Training and Tutorial

    Good Post. Thumps up!!

    ReplyDelete
  2. this is really very useful post about
    java polymorphism
    .
    keep posting.
    thanks

    ReplyDelete
  3. Good work sir, Thanks for the proper explanation about Polymorphism . I found one of the good resource related JAVA and OOPS concepts. It is providing in-depth knowledge on JAVA and OOPS. which I am sharing a link with you where you can get more clear on JAVA and OOPS. To know more Just have a look at this link

    Java Tutorial
    Class and object
    Inheritance
    Polymorphism
    Abstraction
    Encapsulation

    ReplyDelete