java 返回值void,有人可以解释Java中的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?

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?

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

解决方案

Can someone explain a void return type in Java?

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

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?

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.

Bear in mind that the primary the goals of a good API design1 are:

to support the common use-cases well, and

to be easy for programmers to understand.

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

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.

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

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.

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 - There other goals too. Please don't take this out of context ...

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值