What is Polymorphism in Java ?



What is Polymorphism in Java ?

    • Polymorphism in Java is a concept in different ways we can perform a single action.
    • Poly and morphs. The word "poly" means many and "morphs" means forms. Many forms are known as polymorphism.
     Polymorphism in Java

    Polymorphism in Java

    • There are two types of polymorphism in Java:
      • Compile-Time Polymorphism and
      • Runtime Polymorphism.
    • Polymorphism in java we can perform by method overloading and method overriding.

    Dynamic Method Dispatch or Runtime Polymorphism in Java

    • Java supports Runtime Polymorphism is one of the ways is method overriding
    • A call to an overridden method is resolved at run time, rather than compile time it is called as dynamic method dispatch mechanism.
    • At run-time, it depends on the type of the object being referred that determines which version of an overridden method will be executed.
    • A subclass object refers by a superclass variable. This is also known as upcasting. Java uses this statistic to resolve calls to overridden methods at run time.
     Upcasting

    Upcasting

    Example of Java Runtime Polymorphism

      class Bike{  
        void run(){System.out.println("running");}  
      }  
      class Splendor extends Bike{  
        void run(){System.out.println("running safely with 60km");}  
        
        public static void main(String args[]){  
          Bike b = new Splendor();//upcasting  
          b.run();  
        }  
      }  
      

      Output

        running safely with 60km.
        

        Related Searches to What is Polymorphism in Java ?