top button
Flag Notify
    Connect to us
      Site Registration

Site Registration

Polymorphism in Java

–1 vote
1,115 views

                                                                                                                                           Polymorphism in Java

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.

Polymorphism in java is a concept by which we can perform a single action by different ways. Polymorphism is derived from 2 greek words: poly and morphs. The word "poly" means many and "morphs" means forms. So polymorphism means many forms.

Any Java object that can pass more than one IS-A test is considered to be polymorphic. In Java, all Java objects are polymorphic since any object will pass the IS-A test for their own type and for the class Object. It is important to know that the only possible way to access an object is through a reference variable. A reference variable can be of only one type. Once declared, the type of a reference variable cannot be changed. The reference variable can be reassigned to other objects provided that it is not declared final. The type of the reference variable would determine the methods that it can invoke on the object.

                                                                                               

There are two types of polymorphism in java: compile time polymorphism and runtime polymorphism.

Runtime Polymorphism in Java

Runtime polymorphism or Dynamic Method Dispatch is a process in which a call to an overridden method is resolved at runtime rather than compile-time.

In this process, an overridden method is called through the reference variable of a superclass. The determination of the method to be called is based on the object being referred to by the reference variable.

 

Example of Java Runtime Polymorphism

class Bike{  

  void run(){System.out.println("running");}  

}  

class Splender extends Bike{  

  void run(){System.out.println("running safely with 60km");}  

  

  public static void main(String args[]){  

    Bike b = new Splender();//upcasting  

    b.run();  

  }  

}  

Go through this video: (Ref)

posted Sep 12, 2017 by Sourav Kumar

  Promote This Article
Facebook Share Button Twitter Share Button LinkedIn Share Button

...