Does Java support default parameter values?

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

    No, but you can very easily emulate them. What in C++ was:

    public: void myFunction(int a, int b=5, string c="test") { ... }
    

    In Java, it will be an overloaded function:

    public void myFunction(int a, int b, string c) { ... }
    
    public void myFunction(int a, int b) {
        myFunction(a, b, "test");
    }
    
    public void myFunction(int a) {
        myFunction(a, 5);
    }
    

    Earlier was mentioned, that default parameters caused ambiguous cases in function overloading. That is simply not true, we can see in the case of the C++: yes, maybe it can create ambiguous cases, but these problem can be easily handled. It simply wasn't developed in Java, probably because the creators wanted a much simpler language as C++ was - if they had right, is another question. But most of us don't think he uses Java because of its simplicity.

提交回复
热议问题