Why can't I explicitly return void from a method?
It's an interesting question. Since java enforces a return type (void
is a return type) your first statement seems to make sense. I would take this only for convention. Since void
is a placeholder and not an object, it was probably decided to leave it out for language coherency or compiler simplicity.
From JLS
A return statement with no Expression must be contained in the body of a method that is declared, using the keyword void, not to return any value (§8.4), or in the body of a constructor (§8.8).
further
To be precise, a return statement with no Expression always completes abruptly, the reason being a return with no value
A return statement with an expression returns the value of that expression. The type of cancel()
is a void expression - it doesn't have a value.
Logically you want to execute cancel()
, and then return - so that's what you have to say. The two actions (calling cancel()
and then returning) are logically distinct.
Now Java could have a sort of "unit" type instead of void
- but that would affect rather more than just return values.
It's like writing:
void v = (void) 1;
return (v);
So, I think void
is not a type
in Java. In C++, return cancel();
is legal. As a C++ programmer who is familiar with Java the answer is: Many things are not supported in Java syntax. Maybe for simplicity or readibility.
Note: A void f()
declaration is similar to a procedure f()
declaration in pascal and a procedure could not return any value such as functions, so we must call them in a separated statement.