为什么分号不是必需的,但在类定义结束时允许使用分号? [英] Why is the semicolon not required but allowed at the end of a class definition?

查看:169
本文介绍了为什么分号不是必需的,但在类定义结束时允许使用分号?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正试图从C ++转向Java。

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

我想知道的是,在C ++中,在一个类定义之后,一个分号(; )是必需的,但在Java中则不是。

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

也就是说,在C ++中:

That is, in C++:

class Person {
    public:
    string name;
    int number;
}; // Note this semicolon

但在Java中:

class Person {
    public String name;
    public int number;
} // Semicolon is not required

没关系,我理解。

然而,我的问题是

当我在末尾添加分号时,Java也可以工作类定义,如:

Java also works when I add semicolon at end of class definition, like:

class Person {
    public String name;
    public int number;
}; // Now this semicolon is confusing me!

我编译并执行了为Java显示的程序片段,它们都有效。任何人都可以解释为什么会这样吗? Java中类定义末尾的分号代表什么?

I've compiled and executed both the program snippets shown for Java, and they both work. Can anyone explain why this is so? What does the semicolon at the end of a class definition in Java stand for?

如果这个问题质量低,我很抱歉,但我真的需要澄清这个问题。我希望Java专家能帮助我。

I'm sorry if this question is of low quality, but I really need clarification for this. I hope experts in Java will help me.

好吧,我已经看过分类定义中的分号和其他相关问题。

Well, I've already seen Semicolons in a class definition and other related questions.

提前致谢。

推荐答案


我编译并执行了为Java显示的两个程序片段,它们都有效。任何人都可以解释为什么会这样吗?

I've compiled and executed both the program snippets shown for Java, and they both work. Can anyone explain why this is so?

这是允许的,因为Java语法说它是允许的;请参阅 JLS 7.6

It is allowed because the Java Grammar says it is allowed; See JLS 7.6.


Java中类定义末尾的分号代表什么?

What does the semicolon at the end of a class definition in Java stand for?

没什么。它是可选的语法噪音。

Nothing. It is optional "syntactic noise".

JLS解释如下:


额外;出现在编译单元中类型声明级别的标记对编译单元的含义没有影响。 Java编程语言允许使用杂散分号,仅作为对习惯于放置;的C ++程序员的让步。在课堂宣言之后。它们不应该用在新的Java代码中。

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.






(请注意,这不是空语句。空声明( JLS 14.6 )出现在允许语句的语法上下文中。空语句的存在可以改变代码的含义;例如 if(a == b); c(); if(a == b)c();


(Note that this is NOT an "empty statement". An empty statement (JLS 14.6) appears in a syntactic context where a statement is allowed. The presence of an empty statement can change the meaning of your code; e.g. if (a == b) ; c(); versus if (a == b) c();)

这篇关于为什么分号不是必需的,但在类定义结束时允许使用分号?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆