Java Polymorphism
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.
Example: Java Polymorphism
class Polygon {
// 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) {
Rendering Square...
Rendering Circle...
Why Polymorphism?
1. Method Overriding
2. Method Overloading
3. Operator Overloading
Output:
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.
Java Polymorphism
Polymorphism means "many forms", and it occurs when we have many classes
that are related to each other by inheritance.
Example
class Animal {
}
Remember from the Inheritance chapter that we use the extends keyword to
inherit from a class.
Example
class Animal {
}
class Pig extends Animal {
class Main {
myAnimal.animalSound();
myPig.animalSound();
myDog.animalSound();