DAY 23 5.2 OVERLOADING. Overloading: allows for making several methods with the same name (method...
-
Upload
osborn-jenkins -
Category
Documents
-
view
216 -
download
0
Transcript of DAY 23 5.2 OVERLOADING. Overloading: allows for making several methods with the same name (method...
DAY 23 5.2 OVERLOADING
Overloading: allows for making several methods with
the same name (method heading) which diff er from
each other in the type of the input and the output of
the function.
It is simply defined as the ability of one function to
perform diff erent tasks.
OVERLOADING IN CODING (RHYMES)
For example, doTask() and doTask(int income) are overloaded
methods. To call the latter, an integer must be passed as a
parameter, whereas the former does not require a parameter,
and is called with an empty parameter fi eld. A common error
would be to assign a default value to the integer in the
second method, which would result in an ambiguous call
error, as the compiler wouldn't know which of the two
methods to use.
OVERLOADING IN CODING (RHYMES)
Example 2: consider the following two methods,
public void print(String word)
and
public void print(String sentence)
Example 2: consider the following two methods,
public void print(String word)
and
public void print(String sentence)
^ These are overloaded methods as compiler doesn’t know which method to call. Outcome: nothing will be printed!
// volume of a cube
int volume(int s) { return(s*s*s); }
// volume of a cylinder double volume(double r,int h) { return(3.14*r*r*h); }
EXAMPLE 3
Excessive overloading may be diffi cult for developers
to understand which overloaded method is being
called simply by reading the code.
OVERLOADING MAKES IT DIFFICULT TO READ CODE
public class AddAmount{ public int mathItems(int a, int b) { return a + b; }
public int mathItems(int c, int d){ return c+c+d+d;}
EXAMPLE 4 – COMPILER CONFUSION
ANY QUESTIONS?
WORK ON ASSIGNMENT #2