Void and return in Java - when to use(Java 中的 void 和 return - 何时使用)
问题描述
我对 void 和 return 有一些困惑".一般来说,我理解 void 用在方法中而不返回任何东西,而当我想向调用代码返回一些东西时,return 用在方法中.
I have some "confusion" about void and return. In general, I understand void is used in methods without returning anything, and return is used in methods when I want to return something to the calling code.
但是在下面的代码中,我可以同时使用两者,我的问题是,使用哪一个?以及如何确定?是关于性能吗?
通常情况下,我在这两种情况下都会得到相同的结果.
Normally, I have the same results in both cases.
public class Calc {
private double number;
Calc (double n)
{
number = n;
}
public void add(double n)
{
number += n;
}
public double add1(double n)
{
return number = number + n;
}
}
谢谢!
推荐答案
这个方法:
public void add(double n)
{
number += n;
}
您更改了 number
的内部状态,但此方法的调用者不知道 number
的最终值.
You change the internal state of number
but the caller of this method doesn't know the final value of number
.
在下面的方法中,您正在向调用者提示 number
的最终值.
In the below method, you are intimating the caller the final value of number
.
public double add1(double n)
{
return number = number + n;
}
我建议保留一个单独的 getNumber()
getter 方法.
I would suggest to keep a separate getNumber()
getter method.
这篇关于Java 中的 void 和 return - 何时使用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:Java 中的 void 和 return - 何时使用


- 如何使用WebFilter实现授权头检查 2022-01-01
- C++ 和 Java 进程之间的共享内存 2022-01-01
- Java包名称中单词分隔符的约定是什么? 2022-01-01
- value & 是什么意思?0xff 在 Java 中做什么? 2022-01-01
- Eclipse 插件更新错误日志在哪里? 2022-01-01
- Jersey REST 客户端:发布多部分数据 2022-01-01
- 从 finally 块返回时 Java 的奇怪行为 2022-01-01
- Safepoint+stats 日志,输出 JDK12 中没有 vmop 操作 2022-01-01
- 将log4j 1.2配置转换为log4j 2配置 2022-01-01
- Spring Boot连接到使用仲裁器运行的MongoDB副本集 2022-01-01