No enclosing instance of type Main is accessible. Must qualify the allocation with an enclosing i...
最近在刷AC,在編譯時(shí)出現(xiàn):
No enclosing instance of type Main is accessible. Must qualify the allocation with an enclosing instance of type Main (e.g. x.new A() where x is an instance of Main).
根據(jù)提示,沒有可訪問的內(nèi)部類的實(shí)例,必須分配一個(gè)合適的內(nèi)部類的實(shí)例(如x.new A(),x必須是內(nèi)部類的實(shí)例。看著這句提示,我。。。
我已經(jīng)用new實(shí)例化了這個(gè)類,為什么還不行呢。
于是仔細(xì)看了一下IDE提示的地方,看了一下代碼,突然發(fā)現(xiàn),一般AC題目的時(shí)候,要求main方法是static的,而我寫的Student內(nèi)部類是非靜態(tài)的,所以無法訪問
最簡(jiǎn)單的改法:將Student改為靜態(tài)方法之后,不再報(bào)錯(cuò)。
這個(gè)錯(cuò)誤很低級(jí),將其總結(jié),提醒自己,之后不可再錯(cuò)。
此處,我們引出另外一個(gè)知識(shí)點(diǎn),Java靜態(tài)方法訪問非靜態(tài)方法的實(shí)現(xiàn)方法有哪些?
不多說,直接上代碼:
1) 將內(nèi)部類修改,變?yōu)橥獠?/strong>
class test{ public static void main(String args[]){ System.out.println(new test1().methodname()); } } class test1{ public String methodname(){ System.out.println("調(diào)用了非靜態(tài)方法"); } }2) 將內(nèi)部類修改為靜態(tài)內(nèi)部類
class test{ public static void main(String args[]){ System.out.println(new test1().methodname()); } public class static test1{ public String methodname(){ System.out.println("調(diào)用了非靜態(tài)方法"); } } }總結(jié)
以上是生活随笔為你收集整理的No enclosing instance of type Main is accessible. Must qualify the allocation with an enclosing i...的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。