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 |

No comments:

Post a Comment