return void in a void method?

和自甴很熟 提交于 2021-02-08 10:17:18

问题


I know I can do this:

void someMethod(){
 return;
 }

but I get a syntax error on

void someMethod(){
return void;
}

Why is the latter not allowed? It makes more sense to me.

Edit: I know what a void method is, and that I don't have to return from it at all(and probably shouldn't, in most cases) but I don't understand why I can't return void from a void method. In my opinion, there should be no keyword in the method declaration (like constructors) if the you are able to write return;.


回答1:


I think both are to be shunned. I prefer this:

void someMethod() {
    // do stuff; no return at bottom
}

I'd be willing to be that you'd find lots of methods in the JDK source code that look like this.




回答2:


When you declare a method as void, you're saying that the method does not return a value. Attempting to return a value, therefore, is illegal. Additionally, return void; has a syntax error because void is not (indeed, cannot be) the name of an in-scope variable.




回答3:


void is a type, not an expression, so trying to write return void is the same as trying to write return int: syntactically invalid.




回答4:


When you call return void;, you are using a reserved keyword in the incorrect manner. Since it would not expect the keyword void in that manner, it would cause an error.

The Void class is an uninstantiable placeholder class to hold a reference to the Class object representing the Java keyword void.

If you would prefer to return something, then you can return null; by parameterizing a type Void like in this answer, but that's unconventional. Best bet is to omit return altogether or just say return;.




回答5:


return x; indicates that control is leaving the method and that its result is the value of x.

return; indicates that control is leaving the method without a result.

The type void is a type with zero values, so for void methods there is no x such that return x makes sense.

All non-void methods must do one of three things:

  1. Fail to exit ever.
  2. Finish abnormally with an exception.
  3. Finish normally with zero or one return values.

Since void is the only type with zero possible values (Classes with private uncalled ctors don't count because of null), there is no possible return in a non-void method such that return makes sense.



来源:https://stackoverflow.com/questions/16406462/return-void-in-a-void-method

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!