Java 是否支持默认参数值? [英] Does Java support default parameter values?

查看:25
本文介绍了Java 是否支持默认参数值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我遇到了一些具有以下结构的 Java 代码:

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

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

public MyParameterizedFunction(String param1, int param2, boolean param3)
{
    //use all three parameters here
}

我知道在 C++ 中我可以为参数分配一个默认值.例如:

I know that in C++ I can assign a parameter a default value. For example:

void MyParameterizedFunction(String param1, int param2, bool param3=false);

Java 支持这种语法吗?这两个步骤的语法更可取的原因有哪些?

Does Java support this kind of syntax? Are there any reasons why this two step syntax is preferable?

推荐答案

不,您找到的结构就是 Java 处理它的方式(即使用重载而不是默认参数).

No, the structure you found is how Java handles it (that is, with overloading instead of default parameters).

对于构造函数,参见 Effective Java:编程语言指南 如果重载变得复杂,则第 1 项提示(考虑静态工厂方法而不是构造函数).对于其他方法,重命名某些情况或使用参数对象会有所帮助.这是当你有足够的复杂性时,区分是困难的.一个明确的情况是您必须使用参数的顺序进行区分,而不仅仅是数字和类型.

For constructors, See Effective Java: Programming Language Guide's Item 1 tip (Consider static factory methods instead of constructors) if the overloading is getting complicated. For other methods, renaming some cases or using a parameter object can help. This is when you have enough complexity that differentiating is difficult. A definite case is where you have to differentiate using the order of parameters, not just number and type.

这篇关于Java 是否支持默认参数值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆