Search code examples
javadefaultoverloading

Is overloading really the only way to get default values for method parameters in Java?


I'm quite new to Java and from Python and PHP, I'm used to default values for function parameters.

So I have a habit of writing methods that are designed to be called from slightly different situations where you want to set only some of the values. For example, in my PHP code, this would be common where I have factory methods that provide object instances with slightly different properties.

In Java, it seems, I have to have one method that expects all parameters and then several overloaded variations that would call that method with some of the parameters set to defaults and some provided by the caller. Which is, well, OK, but can get on my nerves sometimes.

I remember that this already annoyed me in some brief excursions to C++ and ActionScript. Now, do more experienced Java developers have some shortcut for this?

It seems to me that, technically, the question has been answered by the sum of all posts as "Yes, it is". I've opened a wiki post below to collect the various alternative solutions, please contribute if you like. I found all of these very helpful as an inspiration and as learning examples for typical Java constructs.


Solution

  • It seems like, "Yes, it is", except:

    Similar effects could be achieved with varargs as suggested by Paul Whelan or by defining an extra type carrying the parameters as fields with the proper default values as suggested by Jon Skeet. Boris Pavlović adds that his type could be an inner static class to keep things neatly in the right place.

    Cons (Note that this whole question is not about any serious implications, just about convenient tweaks):

    Varargs seem most suitable for passing a variable-length list of values that have very similar form and mostly equivalent meaning, such as a list of names. If used for the purpose stated in the question, the method would have to perform various checks on the list in order to interpret it, which seems not more, but less convenient.

    A special type carrying the parameters seems most useful if the resulting type could be of other uses than just being passed to one particular method, or when it is a more complex set of parameters. If there's 2-4 parameters and some may have default values, it still seems a little more convenient to overload, but that might be a matter of personal taste.