有人可以解释 Java 中的 void 返回类型吗?

2022-01-19 00:00:00 return void java

我见过的唯一 void 返回类型在方法中有 System.out.println 语句.因此,一旦调用该方法,这些字符串就会被打印出来.
难道你不能做返回类型字符串并返回字符串而不是做 void 返回类型吗?

The only void return type I have seen has System.out.println statements in a method. So once the method is called those Strings will be printed.
Couldn't you make the return type string and have the string returned instead of doing void return type?

如果 void 返回类型方法中包含其他方法,您是否可以将返回类型设为该方法给出的值,该值将返回该方法的结果?

If the void return type method has other methods in it could you make the return type the value which the method gives which would return the outcome of that method?

什么时候只能使用 void 返回类型?

When is it that you could only use the void return type?

推荐答案

有人可以解释 Java 中的 void 返回类型吗?

Can someone explain a void return type in Java?

void类型用于声明方法不返回值.

The void type is used to declare that a method does not return a value.

难道不可以直接将返回类型设为String,并将字符串设置为与参数相等,以便在调用方法时显示出来吗?

Couldn't you just make the return type String and set the string equal to the parameter to make it show up when the method is called?

假设你"(或者在这种情况下,PrintStream API 的设计者)可以做到这一点,但这样做没有意义.我正在努力想一个合理的用例,在该用例中 use println 参数 String ...如果它作为结果返回.

Hypothetically "you" (or in this case, the designers of the PrintStream API) could do that, but there is no point in doing it. I am struggling think of a plausible use-case where it would make sense to use the println argument String ... if it was returned as a result.

请记住,良好 API 设计的主要目标包括1:

Bear in mind the primary goals of a good API design include1:

  • 很好地支持常见的用例,并且
  • 让程序员易于理解.

返回没有意义或很少(如果有的话)使用的值的方法(IMO)设计不佳.

Methods that return values that either don't make sense or that are rarely (if ever) used are (IMO) poorly designed.

如果 void 返回类型方法中有其他方法,您是否可以创建返回该方法结果的返回类型方法?

If the void return type method has other methods in it could you make the return type method which would return the outcome of that method?

嗯,我想是的.但是您遇到了与上述相同的问题.如果结果要么很少使用或难以理解(因此难以正确使用),那么返回它可能是糟糕的设计.

Well, I guess so. But you've got the same issues as above. If the result is either rarely used or is hard to understand (and therefore hard to use correctly) then it is probably bad design to return it.

什么时候只能使用 void 返回类型?

When is it that you could only use the void return type?

一种情况是您正在实现或覆盖 interface 或超类中的方法,并且该方法使用 void 返回类型声明.

One case is where you are implementing or overriding a method in an interface or a superclass, and that method is declared with a void return type.

但在孤立的情况下,没有任何情况可以只使用void.(但有很多情况好的设计说最好使用void!)

But in isolation, there are no cases where you can only use void. (But there are lots of cases where good design says that it is best to use void!)

1 - 还有其他目标.请不要断章取义...

相关文章