1. 程式人生 > >java出現“No enclosing instance of type XXX is accessible”

java出現“No enclosing instance of type XXX is accessible”

今天有個師妹問了我這個程式碼問題,想起之前也有同學問過我這個問題,覺得這個問題挺常見,所以就想記錄下,以下內容轉自https://cloud.tencent.com/info/800ee9743312952016098d63555cb743.html

報錯如下:

Question:No enclosing instance of type MermoryGroup is accessible. Must qualify the allocation with an enclosing instance of type MermoryGroup (e.g. x.new A() where x is
an instance of MermoryGroup).

此處輸入圖片的描述

原因如下:

MermoryGroup為內部類,沒有可訪問的內部類MermoryGroup的例項,必須分配一個合適的內部類MermoryGroup的例項(如x.new A(),x必須是MermoryGroup的例項。)

內部類是動態的,也就是開頭以public class開頭。而主程式是public static class main。在Java中,類中的靜態方法不能直接呼叫動態方法。只有將某個內部類修飾為靜態類,然後才能夠在靜態類中呼叫該類的成員變數與成員方法。所以在不做其他變動的情況下,最簡單的解決辦法是將public class改為public static class.

此處輸入圖片的描述

另一種方法:

此處輸入圖片的描述