- Polymorphism in java is a concept by which we can perform a single action by different ways.
- Polymorphism is the ability of an object to take on many forms.
- There are two types of polymorphism in java
- Compile time polymorphism (Static)
- Runtime polymorphism (Dynamic)
- We can perform polymorphism in java
- Method overloading
- Method overriding.
Method Overloading:
If a class has multiple methods by same name but different parameters, it is called as Method Overloading.
Example of method overloading
class DemoCal { void sum (int a,int b) { System.out.println (a+b); } void sum (int a, int b, int c) { System.out.println (a+b+c); }   public static void main(String args[]) { DemoCal a=new DemoCal (); a.sum (10, 10, 10); a.sum (20, 20); }
Output:30 40
Method Overriding:
If subclass (child class) has the same method as declared in the parent class, it is known as method overriding in java.
Example:
class Bank { int getRateOfInterest(){return 0;} } class SBI extends Bank { int getRateOfInterest(){return 8;} } class ICICI extends Bank { int getRateOfInterest(){return 7;} } class AXIS extends Bank { int getRateOfInterest(){return 9;} } class Test2 { public static void main(String args[]) { SBI s=new SBI (); ICICI i=new ICICI(); AXIS a=new AXIS(); System.out.println ("SBI Rate of Interest: "+s.getRateOfInterest ()); System.out.println ("ICICI Rate of Interest: "+i.getRateOfInterest ()); System.out.println ("AXIS Rate of Interest: "+a.getRateOfInterest ()); } }
Output:
SBI Rate of Interest: 8
ICICI Rate of Interest: 7
AXIS Rate of Interest: 9