Does Java support default parameter values?

后端 未结 25 2183
清歌不尽
清歌不尽 2020-11-22 07:07

I came across some Java code that had the following structure:

public MyParameterizedFunction(String param1, int param2)
{
    this(param1, param2, false);
}         


        
25条回答
  •  被撕碎了的回忆
    2020-11-22 07:24

    Instead of using:

    void parameterizedMethod(String param1, int param2) {
        this(param1, param2, false);
    }
    
    void parameterizedMethod(String param1, int param2, boolean param3) {
        //use all three parameters here
    }
    

    You could utilize java's Optional functionality by having a single method:

    void parameterizedMethod(String param1, int param2, @Nullable Boolean param3) {
        param3 = Optional.ofNullable(param3).orElse(false);
        //use all three parameters here
    }
    

    The main difference is that you have to use wrapper classes instead of primitive Java types to allow null input.Boolean instead of boolean, Integer instead of int and so on.

提交回复
热议问题