什么时候在方法右括号后加分号? [英] When would you put a semicolon after a method closing brace?

查看:25
本文介绍了什么时候在方法右括号后加分号?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我用 Java 编程有一段时间了,我只是第一次遇到这种语法:

public Object getSomething(){return something;};

让我感兴趣的是最后一个分号.它似乎不会导致编译器错误,据我所知不会产生运行时错误,所以它似乎是有效的语法.我什么时候会使用这种语法?或者它只是允许但通常不使用的东西?

解决方案

它被语法允许作为对无害语法错误的让步,但它并不普遍使用,并且没有任何不同的意思(与不使用分号一样).

就像一个 }; inside 一个方法(比如在一个 if 块之后)是一个空语句并且被允许,一个错误的分号outside 方法被认为是空声明并且是允许的.

具体来说,来自 Java 语言规范的以下产品 允许这样做:

<块引用>

ClassBodyDeclaration:;[静态] 块ModifiersOpt MemberDecl

I've been programming in Java for a while, and I've just come across this syntax for the first time:

public Object getSomething(){return something;}; 

What's interesting me is the final semicolon. It doesn't seem to be causing a compiler error, and as far as I know isn't generating runtime errors, so it seems to be valid syntax. When would I use this syntax? Or is it just something that is allowed but generally not used?

解决方案

It's allowed by the grammar as a concession to harmless syntax errors, but it's not generally used and doesn't mean anything different (than leaving the semicolon out).

Just as a }; inside a method (such as after an if block) is a null statement and is allowed, an errant semicolon outside a method is considered a null declaration and is allowed.

Specifically, the following production from the Java Language Specification allows this:

ClassBodyDeclaration:
  ; 
  [static] Block
  ModifiersOpt MemberDecl

这篇关于什么时候在方法右括号后加分号?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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