Polymorphism-in-Java 17
Polymorphism-in-Java 17
Topperworld.in
Polymorphism in Java
That is, the same entity (method or operator or object) can perform
different operations in different scenarios.
// renders Square
public void render() {
System.out.println("Rendering Square...");
}
}
// renders circle
public void render() {
System.out.println("Rendering Circle...");
Java Programming
}
}
class Main {
public static void main(String[] args) {
Output
Rendering Square...
Rendering Circle...
The main purpose of the render() method is to render the shape. However,
the process of rendering a square is different than the process of rendering
a circle.
Types of Polymorphism
Compile-time polymorphism
Run-time polymorphism
Java Programming
Compile-time Polymorphism :
Compile-time polymorphism in Java is
also called static polymorphism or static method dispatch. It can be
achieved by method overloading. In this process, an overloaded method is
resolved at compile time rather than resolving at runtime.
In a Java class, we can create methods with the same name if they differ
in parameters. For example,
This is known as method overloading in Java. Here, the same method will
perform different operations based on the parameter.
class Pattern {
class Main {
public static void main(String[] args) {
Java Programming
Output:
**********
##########
In the above example, we have created a class named Pattern. The class
Run-time Polymorphism :
Run-time polymorphism in Java is also
called Dynamic method dispatch. It can be achieved by method overriding.
In this process, Instead of resolving the overridden method at compile-
time, it is resolved at runtime.
If the same method is present in both the superclass and the subclass.
Then, the method in the subclass overrides the same method in the
superclass. This is called method overriding.
In this case, the same method will perform one operation in the superclass
and another operation in the subclass. For example,
class Language {
public void displayInfo() {
System.out.println("Common English Language");
}
}
class Main {
public static void main(String[] args) {
}
}
Output:
named Java.
Characteristics of Polymorphism :