Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 303
Hanno Fietz Avatar asked Jan 26 '26 21:01

Hanno Fietz


2 Answers

Another option is a variation on the builder pattern - you have a type which represents all the parameters, construct an instance of that type (which defaults accordingly), set the properties you want, and then pass the result into the original method, or add a method in the "parameter type" to call the method for you.

You can see this in action in the standard libraries, with the ProcessBuilder and Process classes.

like image 127
Jon Skeet Avatar answered Jan 29 '26 12:01

Jon Skeet


see varargs

http://www.java-tips.org/java-se-tips/java.lang/using-the-varargs-language-feature.html

(Updated URL; this comment added because stackoverflow requires >30 chars)

like image 45
Paul Whelan Avatar answered Jan 29 '26 11:01

Paul Whelan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!