Professional Documents
Culture Documents
Polymorphism
Polymorphism
Polymorphism means "many forms", and it occurs when many classes are related to
each other by inheritance. Polymorphism is derived from 2 Greek words: poly and
morphs. The word "poly" means many and "morphs" means forms. So polymorphism
means many forms.
When attributes and methods from another class are inherited to a class,
Polymorphism uses those methods to perform different tasks. This allows performing
a single action in different ways.
class Animal {
public void animalSound() {
System.out.println("The animal makes a sound");
}
}
class Main {
public static void main(String[] args) {
Animal myAnimal = new Animal(); // Create a Animal object
Animal myPig = new Pig(); // Create a Pig object
Animal myDog = new Dog(); // Create a Dog object
myAnimal.animalSound();
myPig.animalSound();
myDog.animalSound();
}
}
There are two types of polymorphism in Java:
Compile-time Polymorphism, and
Runtime Polymorphism.
class A{}
class B extends A{}
A a=new B(); //upcasting
For upcasting, the reference variable of class type or an interface type can be used.
interface I{}
class A{}
class B extends A implements I{}
B IS-A A
B IS-A I
B IS-A Object // Since Object is the root class of all classes in Java
Runtime Polymorphism with Data Member
class Bike {
int speedlimit=90;
}
class Honda3 extends Bike {
int speedlimit=150;
Overriding vs Overloading
Overriding implements Runtime 1. Overloading implements Compile-time
Polymorphism. Polymorphism.
The Method Overriding occurs between 2. Overloading occurs between the
superclass and subclass. methods in the same class.
Overridden Methods have the same 3. Names of Overloaded Method are the
signature i.e. same name and method same but the parameters are different.
arguments.
With Overriding, the method call is With Overloading, the method to call is
determined at the runtime based on the determined at the compile-time.
object type.
If Overriding breaks, it can cause serious If Overloading breaks, the compile-time
issues in the program because the effect error will come and it’s easy to fix.
will be visible at runtime.
****