Java构造函数/方法与可选参数? [英] Java constructor/method with optional parameters?

查看:894
本文介绍了Java构造函数/方法与可选参数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


可能重复:

Java可选参数

我知道在PHP中,如果你想调用函数使用较少的参数声明函数,如:

I know that in PHP if you want to call a function with less parameters you declare the function like:

function foo(int param1, int param2 = "2");

现在我可以调用 foo(2) param2 将设置为2。

and now I can call foo(2) and param2 will be set to 2.

我试图在Java构造函数中执行此操作,是不可能的。有没有办法做,或者我只需要声明两个构造函数?

I tried to do this in a Java constructor but it seems it isn't possible. Is there a way to do this or i just have to declare two constructors?

谢谢!

推荐答案

Java在构造函数或方法中没有带有默认值的可选参数的概念。你基本上停留在超载。但是,你很容易链接构造函数,所以你不需要重复代码:

Java doesn't have the concept of optional parameters with default values either in constructors or in methods. You're basically stuck with overloading. However, you chain constructors easily so you don't need to repeat the code:

public Foo(int param1, int param2)
{
    this.param1 = param1;
    this.param2 = param2;
}

public Foo(int param1)
{
    this(param1, 2);
}

这篇关于Java构造函数/方法与可选参数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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