Polymorphism
Polymorphism is one of the most important feature of Object Oriented Programming. Polymorphism means one thing having several forms.In java polymorphism has two types:
- Method Overloading is also called compile time polymorphism (static binding)
- Method Overriding is also called Runtime polymorphism (dynamic binding)
Method Overloading
Overloaded methods can be reused as the same method name in a class, but with different arguments and optionally , a different return type
Example
A search method on Banking System, to search its customer by name, or by address or by dob, or by phone number, or by customer id.
Sample Code
boolean search(int custid) boolean search(String name,String address) boolean search(String name,Date dob) boolean search(String name,String phoneno)
Example to show method overloading :
class Calculator { public void add(int x,int y) { System.out.println(x+y); } public void add(int x,int y, int z) { System.out.println(x+y+z); } public void add(float x,float y) { System.out.println(x+y); } public int add(long x,long y) { return (x+y); } public static void main(String args[]) { Calculator obj=new Calculator(); obj.add(10,20); obj.add(10,20,30); obj,add(10.1f,20.2f); obj.add(10l,20l); } }