Previous | Home | Next |
Polymorphism in java is a concept by which we can perform a single action by different ways. When two or more same statements having different meaning then it is called as polymorphism. Polymorphism is derived from 2 greek words: poly and morphs. The word "poly" means many and "morphs" means forms. The most common use of polymorphism in OOP occurs when a parent class reference is used to refer to a child class object. There are two types of polymorphism in java: compile time polymorphism (static binding)and runtime polymorphism(dynamic binding). We can perform polymorphism in java by method overloading and method overriding. Method overloading is an example of static polymorphism, while method overriding is an example of dynamic polymorphism. Polymorphism means one name and many forms.
Types of Ploymorphism
- Method Overloading.
- Method Overriding.
- Method Overloading
Method overloading means there are several methods present in a class having the same name but different types/order/number of parameters. When two or more methods of same name in a class, provided that there argument list or parameters are different. This concept is known as Method Overloading. Method overloading increases the readability of the program.
Different ways to overload the method:
- By changing number of arguments
- By changing the data type
- Overloading can take place in the same class or in its sub-class.
- Constructor in Java can be overloaded.
- Overloaded methods must have a different argument list.
- The parameters may differ in their type or number, or in both.
- They may have the same or different return types.
- It is also known as compile time polymorphism.
Example: int sum(int a,int b); int sum(int a,int b,int c);
Example: float sum(int a,float b); float sum(float a,int b);
Rules for Method Overloading
Example :
// Method Overloading by changing the no. of arguments class Calculation { 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[]) { Calculation obj=new Calculation(); obj.sum(10,10,10); obj.sum(20,20); } }
output :
30 40
Example :
//Method Overloading by changing data type of argument class Calculation2 { void sum(int a,int b) { System.out.println(a+b); } void sum(double a,double b) { System.out.println(a+b); } public static void main(String args[]) { Calculation2 obj=new Calculation2(); obj.sum(10.5,10.5); obj.sum(20,20); } }
output :
21.0 40
Previous Home Next