java中的nested-class和inner-class

來源:互聯網
上載者:User

參考了這篇文章:

http://docs.oracle.com/javase/tutorial/java/javaOO/nested.html

nested-class和inner-class的區別:

Nested classes are divided into two categories: static and non-static. Nested classes that are declared
static are simply called static nested classes. Non-static nested classes are called
inner classes.

因此下例中StaticNestedClass是嵌套類,InnerClass是內部類。

class OuterClass {    ...    static class StaticNestedClass {        ...    }    class InnerClass {        ...    }}

nested-class和inner-class都是外層類的成員變數。只不過一個是靜態,一個是非靜態。

因此,nested-class和inner-class都可以被聲明為private,public,protested或package private (這裡回憶一下,普通的class在聲明時只能是public或package private的)。

但是有靜態和非靜態不同可知:nested-class是和類相關的,而inner-class是和執行個體相關的。因此可以不執行個體化對象,就直接存取nested-class,而必須執行個體化類才能訪問inner-class。而nested-class不能訪問外層類的其他成員變數或方法,而inner-class則可以。

這裡還有一個有意思的事:因為inner-class是非靜態成員變數,因此inner-class中不能再定義靜態變數或方法了。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.