Does Java support default parameter values?

后端 未结 25 1589
清歌不尽
清歌不尽 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:40

    If you really want to, you can check it manually by using null:

    public MyParameterizedFunction(String param1, int param2, boolean param3)
    {
        if(param3 == null) {
            param 3 = false;
        }
    }
    

    However i heavily recommend using something else, like overloading or a static factory. Maybe you can get away with this, but it can lead to unexcspected behavior. For example you could have an error in your code, so that your boolean never gets a value. In this case you would not get a NullPointerException. Instead it will look like it was set to false, which can be very confusing to debug.

    0 讨论(0)
提交回复
热议问题