Java Polymorphism
Java Polymorphism
In this tutorial, we will learn about Java polymorphism and its implementation
with the help of examples.
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...");
}
}
class Main {
public static void main(String[] args) {
Output
Rendering Square...
Rendering Circle...
Why Polymorphism?
Polymorphism allows us to create consistent code. In the previous example,
we can also create different methods: renderSquare() and renderCircle() to
render Square and Circle , respectively.
This will work perfectly. However, for every shape, we need to create different
methods. It will make our code inconsistent.
1. Method Overriding
2. Method Overloading
3. Operator Overloading
class Main {
public static void main(String[] args) {
Output:
Based on the object used to call the method, the corresponding information is
printed.
Working of
Java Polymorphism
Note: The method that is called is determined during the execution of the
program. Hence, method overriding is a run-time polymorphism.
This is known as method overloading in Java. Here, the same method will
perform different operations based on the parameter.
class Main {
public static void main(String[] args) {
Pattern d1 = new Pattern();
Output:
**********
##########
In the above example, we have created a class named Pattern . The class
contains a method named display() that is overloaded.
Here, the main function of display() is to print the pattern. However, based on
the arguments passed, the method is performing different operations:
prints a pattern of * , if no argument is passed or
prints pattern of the parameter, if a single char type argument is passed.
The + operator is used to add two entities. However, in Java, the + operator
performs two operations.
1. When + is used with numbers (integers and floating-point numbers), it
performs mathematical addition. For example,
int a = 5;
int b = 6;
// + with numbers
int sum = a + b; // Output = 11
2. When we use the + operator with strings, it will perform string concatenation
(join two strings). For example,
// + with strings
name = first + second; // Output = Java Programming
Here, we can see that the + operator is overloaded in Java to perform two
operations: addition and concatenation.
Note: In languages like C++, we can define operators to work differently for
different operands. However, Java doesn't support user-defined operator
overloading.
Polymorphic Variables
A variable is called polymorphic if it refers to different values under different
conditions.
class Main {
public static void main(String[] args) {
Output:
I am Programming Language.
I am Object-Oriented Programming Language.
REFERENCES: https://www.programiz.com/java-programming/polymorphism