Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
264 views
in Technique[技术] by (71.8m points)

Can someone explain a void return type in Java?

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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 the primary goals of a good API design include1:

  • 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 ...


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...