Java 中 modifer 'public' is reduntant for interface methods

來源:互聯網
上載者:User

標籤:

http://androidren.com/index.php?qa=322&qa_1=java-%E4%B8%AD-modifer-public-is-reduntant-for-interface-methods

經常會看到介面上寫了public修飾方法,然後IDE,比如:Eclipse或者IDEA經常會提示public是多餘的。後來就查了一下。java預設介面的方法是public和abstract的,所以真沒必要。同時,如果你使用private或者protected都會報錯。

所以,安心刪除public吧。

http://stackoverflow.com/questions/17011374/are-public-and-public-final-redundant-for-interface-methods

You cannot have a final method declared in an interface. Fields are always final but methods are always abstract (and never final). You cannot define an interface method that is to be implemented only by classes in the same package.* From section 9.3 of the Java Language Specification:

Every field declaration in the body of an interface is implicitly public, static, and final. It is permitted to redundantly specify any or all of these modifiers for such fields.

and from section 9.4:

Every method declaration in the body of an interface is implicitly public (§6.6).

Every method declaration in the body of an interface is implicitly abstract, so its body is always represented by a semicolon, not a block.

It is permitted, but discouraged as a matter of style, to redundantly specify the public and/or abstract modifier for a method declared in an interface.

* As Paul Bellora points out in a comment, you can make the interface itself package-private (or protected, or even private) if you want to restrict its visibility.


In addition, an interface can contain constant declarations. All constant values defined in an interface are implicitly publicstatic, and final. Once again, you can omit these modifiers.

另外,所有常量值預設都是public static final,不用添加。

Java 中 modifer 'public' is reduntant for interface methods

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.