Why is the semicolon not required but allowed at the end of a class definition?

前端 未结 5 1431
忘了有多久
忘了有多久 2020-12-18 18:57

I\'m trying to shift from C++ to Java.

What I wonder is, in C++, after a class definition, a semicolon (;) is required, but in Java it isn\'t.

T

5条回答
  •  情歌与酒
    2020-12-18 19:59

    In the early days, allowing this was one of the ways in which Java was made more familiar to C/C++ programmers. This familiarity was important to the adoption of Java.

    Here's how it works syntactically.

    After a top-level class, it works because a compilation unit contains this sequence, according to JLS 7.3:

    CompilationUnit:
     PackageDeclaration(opt) ImportDeclarations(opt) TypeDeclarations(opt)
    

    And a type declaration is any one of the following, according to JLS 7.6:

    TypeDeclaration:
       ClassDeclaration
       InterfaceDeclaration
       ;
    

    After a member class, nested in some other class, it works because a semicolon can be a class member declaration, according to JLS 8.1.6:

    ClassMemberDeclaration:
        FieldDeclaration
        MethodDeclaration
        ClassDeclaration    
        InterfaceDeclaration
        ;
    

    After a local class, inside a method, it works because a semicolon can be an empty statement, according to JLS 14.6:

    EmptyStatement:
        ;
    

提交回复
热议问题