Professional Documents
Culture Documents
POLYMORPHISM
4/6/2024
Contents
1. Introduction
2. Demonstrating polymorphism concepts with super
classes and subclasses
3. Abstract classes and methods
4. Multiple inheritance and interfaces
4/6/2024
Introduction
4
4/6/2024
5
4/6/2024
6
Compile-time polymorphism
Itis also known as Static Polymorphism.
In this process, the call to the method is resolved at
compile-time.
Compile-Time polymorphism is achieved
through Method Overloading.
◼ This type of polymorphism can also be achieved
through Operator Overloading. However, Java does not
support Operator Overloading.
4/6/2024
7
4/6/2024
8
class Test {
public static void main(String args[]) {
myPrint(5);
myPrint(5.0);
}
static void myPrint(int i) {
System.out.println("int i = " + i);
}
static void myPrint(double d) {
// same name, different parameters
System.out.println("double d = " + d);
}
}
4/6/2024
9
Runtime polymorphism
Itis also known as Dynamic Binding or Dynamic
Method Dispatch.
In this process, the call to an overridden method is
resolved dynamically at runtime rather than at compile-
time.
Runtime polymorphism is achieved through Method
Overriding.
4/6/2024
10
4/6/2024
11
class Animal {
public static void main(String args[]) {
Animal animal = new Animal();
Dog dog = new Dog();
animal.print();
dog.print();
}
void print() {
System.out.println("Superclass Animal");
}
}
public class Dog extends Animal {
void print() {
System.out.println("Subclass Dog");
}
}
4/6/2024
Contents
1. Introduction
2. Demonstrating polymorphism concepts with super
classes and subclasses
3. Abstract classes and methods
4. Multiple inheritance and interfaces
4/6/2024
Inheritance v/s Polymorphism
13
4/6/2024
Demonstrating polymorphic behavior
14
4/6/2024
Up-casting v/s Down-casting
15
4/6/2024
…
16
4/6/2024
17
4/6/2024
Casting and instanceof
If we know that b is a Parrot, we can cast it
and use Parrot methods:
((Parrot)b).speak()
At runtime, if b is just a Bird, the JVM will throw
a ClassCastException.
To test this, use instanceof:
if (b instanceof Parrot) {
((Parrot)b).speak()) }
Contents
1. Introduction
2. Demonstrating polymorphism concepts with super
classes and subclasses
3. Abstract classes and methods
4. Multiple inheritance and interfaces
4/6/2024
Abstract class
20
4/6/2024
21
public AbstractClassExample()
{
x = 0;
}
} 4/6/2024
Abstract Method
23
4/6/2024
Contents
1. Introduction
2. Demonstrating polymorphism concepts with super
classes and subclasses
3. Abstract classes and methods
4. Multiple inheritance and interfaces
4/6/2024
Interface
25
4/6/2024
27
4/6/2024
29 4/6/2024
30
4/6/2024
31 4/6/2024
32
Questions?
4/6/2024
33
Thank You
4/6/2024