Dynamic Polymorphism in JavaIn Java, polymorphism is a concept of object-oriented programming that allows us to perform a single action in different forms. In this section, we will discuss only the dynamic polymorphism in Java. PolymorphismThe word polymorphism is a combination of two words i.e. ploy and morphs. The word poly means many and morphs means different forms. In short, a mechanism by which we can perform a single action in different ways. Let's understand the meaning of polymorphism with a real-world example. A person in a shop is a customer, in an office, he is an employee, in the home he is husband/ father/son, in a party he is guest. So, the same person possesses different roles in different places. It is called polymorphism. Types of PolymorphismThere are two types of polymorphism in Java:
Dynamic PolymorphismDynamic polymorphism is a process or mechanism in which a call to an overridden method is to resolve at runtime rather than compile-time. It is also known as runtime polymorphism or dynamic method dispatch. We can achieve dynamic polymorphism by using the method overriding. In this process, an overridden method is called through a 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. Properties of Dynamic Polymorphism
Method OverridingIt provides a specific implementation to a method that is already present in the parent class. it is used to achieve run-time polymorphism. Remember that, it is not possible to override the static method. Hence, we cannot override the main() method also because it is a static method. Rules for Method Overriding
We call an overridden method through a reference of the parent class. The type of object decides which method is to be executed and it is decided by the JVM at runtime. Example of Dynamic PolymorphismIn the following example, we have created two classes named Sample and Demo. The Sample class is a parent class and the Demo class is a child or derived class. The child class is overriding the dispaly() method of the parent class. We have assigned the child class object to the parent class reference. So, in order to determine which method would be called, the type of the object would be decided by the JVM at run-time. It is the type of object that determines which version of the method would be called (not the type of reference). Demo.java Output: Overriding Method Example of Method OverridingDynamicPolymorphismExample.java Output: The child class method is invoked. In the above example, we have used an annotation @Override. It indicates that the child class method is over-writing its base class method. Next TopicJava Robot |
We provides tutorials and interview questions of all technology like java tutorial, android, java frameworks
G-13, 2nd Floor, Sec-3, Noida, UP, 201301, India