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

前端 未结 5 1434
忘了有多久
忘了有多久 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:58

    Java added this just for persons like you who switch from C++!

    In Java, a single semicolon is a declaration that may be written almost everywhere. Its only purpose is to ease the transition from such languages.

    For example, also the following is correct in Java:

    ;;;;;;;;;;
    class X{
        ;;;;;;;;;;;;;;
    } ;;;;;;;;;;;;;;;
    

    A semicolon is simply treated as an empty declaration that does nothing.

    Here is a quote from the spec, paragraph 7.6:

    Extra ";" tokens appearing at the level of type declarations in a compilation unit have no effect on the meaning of the compilation unit. Stray semicolons are permitted in the Java programming language solely as a concession to C++ programmers who are used to placing ";" after a class declaration. They should not be used in new Java code.

    So as you see, this is really just for guys like you :).

    You can even use a line of semicolons as a nice visual separation. However, I strongly advise against this. But it might be good for bragging purposes. E.g.:

    class X {
       // Member variables
       private int i;
    
       ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
       // Constructors
       X(){}
    
       ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
       // Methods
       void foo(){}    
    
    }
    

提交回复
热议问题