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 ...
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…