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

查看:120
本文介绍了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).

对于构造函数, 参见有效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天全站免登陆