• Polymorphism means defining multiple methods with same name.

  • Two types of polymorphism
    1.Static polymorphism
    2.Dynamic polymorphism.

Static polymorphism:

  • Defining multiple methods with same name and with different type of arguments is known as static polymorphism.
  • We can achieve this static polymorphism using method overloading.

Static polymorphism in java with example program


  1. package com.instanceofjava;
  2. class A{
  3.  
  4. public void show(int a){
  5. System.out.println("saidesh");
  6. }
  7.  
  8. public void show(int a,int b){
  9. System.out.println("ajay");
  10. }
  11.  
  12. public void show(float a){
  13. System.out.println("vinod");
  14. }
  15. public static void main(String args[]){
  16.  
  17. A a=new A();
  18.  
  19. a.show(10);
  20. a.show(1,2);
  21. a.show(1.2);
  22.  
  23. }
  24. }
Output:

  1. saidesh
  2. ajay
  3. vinod


Dynamic polymorphism:

  • Defining multiple methods with same name and with same signature in super class and sub class.
  • We can achieve dynamic polymorphism by using method overriding concept in java.
  • Define a method in super class and override same method with same signature in sub class
  • Whenever we call the method on t the object based on the object corresponding class method will be executed dynamically.
Java example program on dynamic polymorphism: (Real time example)

  1. package MethodOverridingExamplePrograms;
  2. public class Vehicle{
  3.  
  4. void Start(){ 
  5. System.out.println("Vehicle started")
  6. }

  7. }


  1. package MethodOverridingExamplePrograms;
  2. public class Car extends Vehicle{
  3.  
  4. void Start(){ 
  5. System.out.println("Car started")
  6. }

  7. }


  1. package MethodOverridingExamplePrograms;
  2. public class Bus extends Vehicle{
  3.  
  4. void Start(){ 
  5. System.out.println("Bus started")
  6. }

  7. }


  1. package MethodOverridingExamplePrograms;
  2. public class Bike extends Vehicle{
  3.  
  4. void Start(){ 
  5. System.out.println("Bike started")
  6. }

  7. }


  1. package MethodOverridingExamplePrograms;
  2. public class Test{
  3.  
  4. public static void startVehicle(Vehicle vh){ 
  5.    
  6. vh.start();


  7.  
  8. }

  9. }

Dynamic polymorphism in java with example program



  •  In the above example based on the object creation at run time corresponding class method will be executed.

Instance Of Java

We will help you in learning.Please leave your comments and suggestions in comment section. if you any doubts please use search box provided right side. Search there for answers thank you.
«
Next
Newer Post
»
Previous
Older Post

No comments

Leave a Reply

Select Menu