Full runtime polymorphism can be achieved in C#, C++, and Java, but Java programs can achieve a limited amount of full runtime polymorphism.
Runtime polymorphism (full or limited) is the ability of an object to change its behavior at runtime based on some condition.
In Java, limited runtime polymorphism can be achieved by using interfaces.
First introduced in 1998, interfaces in java are so useful, and are used in a lot of applications and frameworks.
However, this feature can be glitchy at times, and in this guide, we will explore how to achieve full runtime polymorphism in Java.
- Runtime polymorphism is a type of polymorphism that occurs when the code is compiled.
- It saves a lot of time and memory, but for Java, it requires the JVM to have multiple versions.
- The JVM version can vary depending on the operating system, so Java applications can exhibit runtime polymorphism.
Enable Runtime Polymorphism
- In the Eclipse open the Java SDK folder.
- Click on Help.
- Select Install New Software.
- In the Search box type Java TM Platform, Standard Edition.
- Click next.
- Select the first option labeled Accept License Agreement and click Next.
- Select Browse and locate the folder where you want the JDK installed.
- Click Next.
- Select the option labeled Accept License and click Next.
- Click Finish.
Set the Method Override
- To override a method in Java, add an overriding method with the same signature and return type.
- For example, if class X has a method greeting(), and class Y overrides it, then Y’s greeting() method should have the same signature and return type as that of X’s greeting() method.
- If both the methods have null parameters, then X’s greeting() method should have an empty body; else, Y’s greeting() method should have an empty body.
- Set Class Inheritance
In Java, class inheritance is a fundamental principle.
- It lets you re-define methods in a base class (the superclass) in the subclasses (derived classes).
- The derived class can then override only those methods that it has redefined (i.e., redefined in the derived class).
- For example, class X has two methods greeting() and greeting(String); let’s assume that class Y overrides class X’s greeting() method.
- Y’s greeting() method will have the same signature as class X’s greeting() method, but Y’s greeting(String) method will have a different signature from class X’s greeting(String) method.
- Class inheritance is compulsory for method overriding.
- If the base class has no method with the same signature and return type as that of the method in the derived class, then the class inheritance is ignored.