有人可以解释Java中的void返回类型吗? [英] Can someone explain a void return type in Java?

查看:461
本文介绍了有人可以解释Java中的void返回类型吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我见过的唯一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)就可以做到这一点这样做是没有意义的。我正在努力想到一个看似合理的用例,使用 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 that the primary the goals of a good API design1 are:


  • 很好地支持常见用例,

  • 让程序员很容易理解。

返回值没有意义或很少(如果曾经)使用过的值的方法是(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?

一种情况是您在接口或超类中实现或覆盖方法,并且该方法使用 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 - 还有其他目标。请不要脱离这种情况......

这篇关于有人可以解释Java中的void返回类型吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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