創(chuàng)建Java內(nèi)部類(lèi)的編譯錯(cuò)誤處理
在創(chuàng)建非靜態(tài)內(nèi)部類(lèi)時(shí),經(jīng)常會(huì)遇到“No enclosing instance of type * is accessible. Must qualify the allocation with an enclosing instance of type *(e.g. x.new A() where x is an instance of *).”這樣的報(bào)錯(cuò),其實(shí)原因只有一點(diǎn),內(nèi)部類(lèi)是依賴(lài)于外部類(lèi)存在的,所以在使用非靜態(tài)內(nèi)部類(lèi)時(shí),要求先實(shí)例化外部類(lèi)才可以使用內(nèi)部類(lèi)。關(guān)于非靜態(tài)內(nèi)部類(lèi),我們可以把它理解成外部類(lèi)的成員變量,我們?cè)谑褂靡粋€(gè)類(lèi)的非靜態(tài)成員變量時(shí)要求先對(duì)類(lèi)進(jìn)行實(shí)例化,然后通過(guò)對(duì)象來(lái)調(diào)用這個(gè)類(lèi)的非靜態(tài)成員變量。這里非靜態(tài)內(nèi)部類(lèi)同外部類(lèi)的關(guān)系,就如同非靜態(tài)成員變量同類(lèi)的關(guān)系一樣。所以在使用非靜態(tài)內(nèi)部類(lèi)時(shí),要求先實(shí)例化外部類(lèi)。
下面我給出例子來(lái)分析一下:
package com.csc.innerclasstest; /** } |
上面的代碼的第16行將會(huì)報(bào)出“No enclosing instance of type OuterClass is accessible. Must qualify the allocation with an enclosing instance of type OuterClass (e.g. x.new A() where x is an instance of OuterClass).”這樣的編譯錯(cuò)誤。錯(cuò)誤的原因如上面紅色字體所述。
解決方法一:將非靜態(tài)內(nèi)部類(lèi)轉(zhuǎn)換成靜態(tài)內(nèi)部類(lèi),即在上面程序的第21行的“Private”后面加上“Static”即可。
解決方法二:先實(shí)例化外部類(lèi),然后通過(guò)外部類(lèi)來(lái)調(diào)用內(nèi)部類(lèi)的構(gòu)造函數(shù),代碼如下:
package com.csc.innerclasstest; /** } |
上面代碼的16行先進(jìn)行了外部類(lèi)的實(shí)例化,第18行通過(guò)外部類(lèi)來(lái)引用內(nèi)部類(lèi),這樣就不會(huì)出現(xiàn)“No enclosing instance of type OuterClass is accessible. Must qualify the allocation with an enclosing instance of type OuterClass (e.g. x.new A() where x is an instance of OuterClass”這個(gè)編譯報(bào)錯(cuò)了。
本文轉(zhuǎn)載自:http://blog.csdn.net/caoshichao520326/article/details/8961297
posted on 2013-05-28 10:23 順其自然EVO 閱讀(170) 評(píng)論(0) 編輯 收藏