方法中不必要的字符串(重载方法)

don*_*uel 0 java

我如何制作一个不需要对象的方法,但如果有的话,它会使用它!

像这样

void cls(String source){
        if(source.isEmpty()){
            source = "Unknown source";
        }
        output.setText("Screen cleared from " + source);
    }
Run Code Online (Sandbox Code Playgroud)

后来当我打电话给我时我能做到

cls();
Run Code Online (Sandbox Code Playgroud)

但它会抛出一个错误,因为它需要一个字符串

cls("string");
Run Code Online (Sandbox Code Playgroud)

但我希望两者都能奏效!

Mat*_*all 7

您使用两个具有相同名称但签名不同的方法(称为重载):

void cls() {
    // ???
}

void cls(String source){
    if(source.isEmpty()){
        source = "Unknown source";
    }
    output.setText("Screen cleared from " + source);
}
Run Code Online (Sandbox Code Playgroud)

或者varargs:

void cls(String... sources){
    if (sources.length > 0) {
        // ???
    }
}
Run Code Online (Sandbox Code Playgroud)

  • @donemanuel您可以根据需要将重载的方法"链接"在一起以获得尽可能多的参数.只需让你的no-args方法使用默认参数调用完整版本.`void cls(){cls("Unknown source",false); 你或者你想要的任何其他默认参数. (4认同)
  • @donemanuel更多方法重载,或重新考虑你的设计. (3认同)