Java optional parameters in method

I want to make a method that requires 1 required parameter and 1 optional parameter, but I found out how to create an optional array in the parameter (int... B), but this is an array. I want to make it, but the value is null or the user enters it. I can make two methods with the same name, but one with a single parameter and one with 2 parameters, But can it use only one method?

thank you

Solution

No, Java does not support optional parameters Another alternative to overloading (which doesn't make much sense for two parameters, but makes sense for more parameters) is to use the builder type representing all parameters – you can provide the builder with a constructor containing the required parameters, and then each optional setter to return the setter to the builder itself So call the method like this:

foo.doSomething(new ParameterBuilder(10).setBar(2).setBaz(10));
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>