創建Java內部類的編譯錯誤處理
在創建非靜態內部類時,經常會遇到“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 *).”這樣的報錯,其實原因只有一點,內部類是依賴于外部類存在的,所以在使用非靜態內部類時,要求先實例化外部類才可以使用內部類。關于非靜態內部類,我們可以把它理解成外部類的成員變量,我們在使用一個類的非靜態成員變量時要求先對類進行實例化,然后通過對象來調用這個類的非靜態成員變量。這里非靜態內部類同外部類的關系,就如同非靜態成員變量同類的關系一樣。所以在使用非靜態內部類時,要求先實例化外部類。
下面我給出例子來分析一下:
package com.csc.innerclasstest; /** } |
上面的代碼的第16行將會報出“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).”這樣的編譯錯誤。錯誤的原因如上面紅色字體所述。
解決方法一:將非靜態內部類轉換成靜態內部類,即在上面程序的第21行的“Private”后面加上“Static”即可。
解決方法二:先實例化外部類,然后通過外部類來調用內部類的構造函數,代碼如下:
package com.csc.innerclasstest; /** } |
上面代碼的16行先進行了外部類的實例化,第18行通過外部類來引用內部類,這樣就不會出現“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”這個編譯報錯了。
本文轉載自:http://blog.csdn.net/caoshichao520326/article/details/8961297