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. }

Comments

Popular posts from this blog

Today Walkin 14th-Sept

Spring Elasticsearch Operations

Hibernate Search - Elasticsearch with JSON manipulation