Javac內部類本地類

來源:互聯網
上載者:User

標籤:cti   one   結構   expr   一點   組合   mem   內部類   interface   

  

One way declared types in Java differ from one another is whether the type is a class (which includes enums) or an interface (which includes annotation types). An independent property of a type is its relation to the surrounding lexical context.A top level class does not appear inside another class or interface. If a type is not top level it is nested. However, there are a number of distinct ways a type can be nested. First, a type can be a member of another type; a member type is directly enclosed by another type declaration. All member types have names; however, some member types are inner classes and others are not. If a type is explicitly or implicitly static, it is not an inner class; all member interfaces are implicitly static. Inner classes also include local classes, which are named classes declared inside of a block like a method or constructor body, and anonymous classes, which are unnamed classes whose instances are created in expressions and statements. Anonymous classes are used to implement specialized enum constants. Inner classes have access to instance variables of any lexically 詞彙方面 enclosing instance; that is, the fields of the object an inner class is created in reference to. However, not all inner classes have enclosing instances; inner classes in static contexts, like an anonymous class used in a static initializer block, do not.The Venn diagram below shows how these distinctions relate and combine; in particular, member-ness and inner-ness are not orthogonal properties.

 

 

(1)嵌套靜態類是任何一個在另外一個類或者介面的代碼體中聲明的類,它作為外嵌類或者介面的靜態成員。嵌套靜態類的行為類似於頂級類,唯一的差別是嵌套靜態類前除了有 Java 包的名字以外還有外嵌類的名字。嵌套靜態類是靜態成員,因此沒有 this 指標指向外嵌類的執行個體,也就是說嵌套靜態類不能訪問外嵌類的執行個體資料。當一個重要的資料結構緊密的關聯與外嵌類,並且該資料結構有足夠的內容保證它能夠擁有一個類的時候,一般情況下我們可以使用嵌套靜態類。 內部類有三種形式:成員類、本地類和匿名類,每個類依次都是對它前一個類的改進。 (2)內部類的可視範圍是它的直接外嵌類(這一點和嵌套靜態類不同,嵌套類在其外嵌類之外也是可視的),也就是說內部類可以直接引用外嵌類中的任何成員。因為內部類與外嵌類的執行個體相關,所以內部類擁有兩個 this 指標,一個指向內部類的執行個體本身,一個指向外嵌類執行個體。內部類的一個主要用途是用於 GUI 的事件處理常式。 (3)本地類是在代碼塊中聲明的,因此它不是外嵌類的成員。一般來說,本地類在方法中進行聲明。成員類和本地類的差別很小,通過把本地類移到方法的外部,我們可以很容易得把它轉換成為成員類。它們兩個之間最重要的差別是,本地類只能訪問 final 的變數或者參數。   (4)匿名類允許我們把類的定義和執行個體的分配組合在一起。無須象其它任何嵌套類那樣進行聲明,我們可以直接用 new SomeClass() 執行個體化對象,並且在執行個體化的位置把整個類的實現都放在花括弧中。

 

 

 

 

 

參考:

(1)深入理解為什麼Java中方法內定義的內部類可以存取方法中的局部變數

(2)

 

Javac內部類本地類

聯繫我們

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