java optional parameter in methods

∥☆過路亽.° 提交于 2019-12-06 01:03:34

No, Java doesn't support optional parameters. Another alternative to overloading (which doesn't make much sense for two parameters but does make sense for more) is to use a builder type which represents all the parameters - you can provide a constructor for the builder which contains the required parameters, and then a setter for each of the optional ones, making the setter return the builder itself. So calling the method becomes something like:

foo.doSomething(new ParameterBuilder(10).setBar(2).setBaz(10));
John

What you are looking for is default arguments support. Java doesn't have this capability but it more or less simulates this capability.

One simple way is to use method overloading.

Another approach is to identify special cases directly and then substitute the default values.

Here's an example of mixing both of those approaches by Ivo Limmen:

public void test() {
   this.test(null, null);
}
public void test(String p1) {
   this.test(null, null);
}
public void test(String p1, String p2) {
   if(p1 == null) {
      ...
   } else {
      ...
   }
   if(p2 == null) {
      ...
   } else {
      ...
   }
}

A very interesting approach I found is to use Design Builder pattern. There is an example here

There is also an interesting discussion here

No, this is exactly what method overloading is for

There are no "default" values for parameters in Java's methods. Either use varargs or method overloading.

In java, this is accomplished by something called method overloading. You can create multiple methods with the same name, but different parameters.

For example:

void method1(String arg1){ 
  // only one argument, here you can delegate the work of this method to the implementation that takes the most parameters and pass null for the optional parameters.
    method1(arg1, null);
}

void method1(String ar1, String arg2){
  // do work, handle the case where arg2 is null.
}

Clients of your code can call either one. To them, it appears as if the second argument is optional.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!