[code="java"]public class ClassName extends ParentClassName
{
public ClassName () {;}
}[/code]

Java构造函数中的单个分号是什么含义?
- 写回答
- 好问题 0 提建议
- 关注问题
- 邀请回答
-
4条回答 默认 最新
- qwe_rt 2010-05-08 01:18关注
这个问题可以从java规范文档解释之。
首先我们来看看构造函数的词法定义:
红色的opt表示可有可无。
[b]ConstructorBody:[/b]
{ ExplicitConstructorInvocation[color=red][size=xx-small]opt[/size][/color] BlockStatements[color=red][size=xx-small]opt[/size][/color]}接着下面是BlockStatements的词法定义:
[b]BlockStatements:[/b]
BlockStatement
BlockStatements BlockStatement
[b]BlockStatement:[/b]
LocalVariableDeclarationStatement
ClassDeclarationStatement
接下来,看看Statement的词法定义:
[b]Statement:[/b]
StatementWithoutTrailingSubstatement
LabeledStatement
IfThenStatement
IfThenElseStatement
WhileStatement
ForStatement从上面我们看到Statement由if label while for等语句组成。
接下来看看statement中第一个StatementWithoutTrailingSubstatement词法定义:
[b]StatementWithoutTrailingSubstatement:[/b]
Block
EmptyStatement
ExpressionStatement
AssertStatement
SwitchStatement
DoStatement
BreakStatement
ContinueStatement
ReturnStatement
SynchronizedStatement
ThrowStatement
TryStatement可以注意看看第二个定义EmptyStatement.指的是空statement。
最后看看statement的词法定义。
[b]EmptyStatement:[/b]
;
java规范中对此如下说:[quote]
An empty statement does nothing.
Execution of an empty statement always completes normally.[/quote]=================================
一路走下来,有点费劲,但是总算把问题弄清楚了,为什么构造函数、方法等中可以只有分号(;),其实跟“{ }”这样没区别。
所以甚至可以这样写代码:
[code="java"]if(true){;}[/code][color=gray]详细分析参考:The Java™ Language Specification Third Edition[/color]
本回答被题主选为最佳回答 , 对您是否有帮助呢?解决 无用评论 打赏 举报