Polymorphism is the ability of an object to take on many forms. The most common use of polymorphism in OOP occurs when a parent class reference is used to refer to a child class object. Any Java object that can pass more than one IS-A test is considered to be polymorphic
There are two types of polymorphism in java: compile time polymorphism and runtime polymorphism. We can perform polymorphism in java by method overloading and method overriding.
Example of method overloading
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class OverloaddingDemo{ | |
void sum(int a, int b){ | |
System.out.println("Adding a+b:"+(a+b)); | |
} | |
void sum(int a, int b, int c ){ | |
System.out.println("Adding a+b+c:"+(a+b+c)); | |
} | |
public static void main(String args[]){ | |
OverloaddingDemo ad = new OverloaddingDemo(); | |
ad.sum(25,30); | |
ad.sum(25,30,20); | |
} | |
} |
Example of method overriding
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Dept{ | |
void address(){ | |
System.out.println("Acadimic Building , Just"); | |
} | |
} | |
class Cse extends Dept{ | |
void address(){ | |
System.out.println(" 2nd floar , Acadimic Building , Just"); | |
} | |
public static void main(String args[]){ | |
Dept d = new Dept(); | |
Cse ad = new Cse(); | |
d.address(); | |
ad.address(); | |
} | |
} | |