Object Oriented Programming
Introduction to Java
Lecture# 12
Polymorphism in Java (OOP concepts)
Batch: NUML BSCS [2nd semester]
Lecture Slides by Engr. Mehwish Shaikh
Introduction to Java Programming Language
Polymorphism in Java
Polymorphism in Java can be achieved in two ways
i.e., method overloading and method overriding.
Polymorphism in Java is mainly divided into two types.
Compile-time polymorphism can be achieved by method
overloading, and Runtime polymorphism can be
achieved by method overriding.
Introduction to Java Programming Language
Java Method Overriding
During inheritance in Java, 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.
The method that is called is determined during the
execution of the program. Hence, method overriding is
a run-time polymorphism.
Example 1: Polymorphism using method overriding
Introduction to Java Programming Language
Java Method Overloading
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.
Example 2: Polymorphism using method overloading
Java Constructor Overloading
Constructor overloading is based on the concept of
polymorphism, where different constructors with the
same name but different parameter lists can be called
based on the arguments passed during object creation.
This enables the class to accommodate different
scenarios and simplify object instantiation.
Introduction to Java Programming Language
Java Operator Overloading
Some operators in Java behave differently with different operands.
For example,
• + operator is overloaded to perform numeric addition as well as
string concatenation, and
• operators like ‘&’ , ‘|’ , ‘!’ are overloaded for logical and bitwise
operations.
In languages like C++, we can define operators to work differently
for different operands. However, Java doesn't support user-defined
operator overloading.
Let's see how we can achieve polymorphism using operator
overloading.
Introduction to Java Programming Language
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.
2. When we use ‘+’ operator with strings, it will perform string
concatenation (join two strings).
Introduction to Java Programming Language
Polymorphic Variables
A variable is called polymorphic if it refers to different
values under different conditions.
Object variables (instance variables) represent the
behavior of polymorphic variables in Java. It is
because object variables of a class can refer to
objects of its class as well as objects of its subclasses.