2. SSBN Degree College, ATP M Vishnuvardhan
Introduction
Polymorphism is a Greek word which
means one name multiple forms (Ploy –
many & morphism – forms). There are two
type of Polymorphisms.
Compile Time Polymorphism ( Method
Overloading )
Run Time Polymorphism. ( Method Overriding )
3. SSBN Degree College, ATP M Vishnuvardhan
Method Overloading
Declaring multiple methods with same
name in a class is called Method overloading
or compile time polymorphism.
Eg:
class A
{
======
void process()
{ --- }
void process( --- )
{--- }
=====
}
Method
overloading
4. SSBN Degree College, ATP M Vishnuvardhan
Rules for Overloading
To overload multiple methods in java any two methods
must satisfy any of the following conditions. Other wise
those methods are not considered as overloaded and also
compile time error is generated
There must be difference number of parameters (OR)
There must be difference in type of parameters
Valid examples
int add(int a, int b) { }
int add(int a, int b, int c) { }
int add(float a, float b) { }
Invalid examples
int add(int a, int b) { }
int add(int x, int y) { }
float add(int a, int b) { }
5. SSBN Degree College, ATP M Vishnuvardhan
Compiler in Action
When ever a method is invoked the java compiler decides and
calls the appropriate method basing on the no of parameters
or the type of parameters. If any two methods have same
signature then ambiguity arises.
int add(int a, int b) { }
int add(int a, int b, int c) { }
int add(float a, float b) { }
Note: return type doesn’t help in deciding the function
int add(int x, int y) { }
float add(int a, int b) { }
add(10,25)
add(10,25,35)
add(25.45,51.20)
add(10,25)
add(10,25)