Showing posts with label function. Show all posts
Showing posts with label function. Show all posts

Tuesday, 12 November 2013

Function over-loading in Java - part 2

Refer to : http://mycodedock.blogspot.in/2013/11/function-over-loading-in-java-part-1.html

Now, we wish to create a function called calcAns() that takes in two integers - int a, int b and returns a*b. However, at times we also need to calculate answer for three integers - int a, int b, int c which should return a*b*c.

Since the nature of both these functions is very similar, it would be very handy if we could use the same function name for both these functions. Is it possible? Lets find out!


Note that the compiler automatically decides which *version* of calcAns() to use when you call it depending upon number of arguments.

Thumb rule for using function over-loading

  • The functions much have same names
  • The functions must differ either by number of arguments or type of arguments or both (else it would be redundant)
  • The functions may have different return types


| Advertisement |

Function over-loading in Java - part 1

Let us suppose we wish to create a function myFunc() that can take in three integers as arguments - int x, int y, int z and returns (x*y)+z. It is fairly easy to write such a function. But what if later on we wish to give the same sort of functionality for three arguments of type - double, lets say - double a, double b, double c. Can this be achieved without creating a function with a new name?

Lets have a look at the code given below -


Note that the compiler automatically detects which *version* of the method to use when you call myFunc() depending upon the type of arguments.

| Advertisement |