u010183036 2010-05-07 23:08
浏览 269
已采纳

Java构造函数中的单个分号是什么含义?

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

  • 写回答

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
    ClassDeclaration

    Statement

    接下来,看看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]

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(3条)

报告相同问题?