Sunday, 4 March 2012

Method

Method
What:
It is a named block of code
Its components are:
1. Return Type (RT)
2. Function Name (FN)
3. Parameter List (PL)
4. Body
Function Header: this is also called declaration
RT FN(PL)
Function Signature:
FN(PL)
Imp:
A function can call other function
A function cannot be defined inside another function
===
Method Overloading
What:
It is a mechanism of writting a number of functions which have (obviously) have the same name and different parameter list.
Why:
So that we do not have to remember different names of several functions to do similar tasks
How:
by writting multiple functions with same name and different parameter list as shown below
e.g.1
int sum(int a, int b)
{
 return (a+b);
}
int sum(int a, int b, int c)
{
 return (a+b+c);
}
both sum functions have same name but differ in the number of parameters
Different ways to change Parameter List:
1. Number of Parameters
2. Order of Parameters
3. DataType of Parameters
Imp:
The return type plays no role in method overloading
e.g.2
float sum(int a, int b)
{
 return (a+b);
}
// different number of parameters
float sum(int a, int b, int c)
{
 return (a+b);
}
//different data types
float sum(int a, float b)
{
 return (a+b);
}
//different order of parameters
float sum(float a, int b)
{
 return (a+b);
}
float sum(float a, float b)
{
 return (a+b);
}
Pros:
Saves the end developer from remembering multiple names for similar tasks with different input requirements
Cons:
There is some overhead for the compiler because the compiler has to match the name and parameter list in case of method overloading whereas it will have to match the name only if method overloading is not being done
Comment:
No work reduction for the main developer because the functions with different signatures must be written in any case
QnA:
Q if there are two functions with different name but same parameter list, is it method overloading
A No. Method overloading must have same function/method name
Q Can every function/method be overloaded
A yes

No comments:

Post a Comment