如何设置默认方法的参数值? [英] how to set default method argument values?

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

问题描述

是否可以在Java中设置默认方法参数值?

Is it possible to set the default method parameter values in Java?

示例: 如果有方法

public int doSomething(int arg1, int arg2)
{
//some logic here
    return 0;
}

是否可以修改给定的方法以便能够在有参数和无参数的情况下调用它?

is it possible to modify the given method in order to be able to call it with and without parameters?

示例:

doSomething(param1, param2);
doSomething();

谢谢!

推荐答案

您可以通过方法重载来实现.

public int doSomething(int arg1, int arg2)
{
        return 0;
}

public int doSomething()
{
        return doSomething(defaultValue0, defaultValue1);
}

通过创建此无参数方法,您允许用户使用在无参数方法的实现中提供的默认参数来调用parameterfull方法.这称为重载方法.

By creating this parameterless method you are allowing the user to call the parameterfull method with the default arguments you supply within the implementation of the parameterless method. This is known as overloading the method.

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

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