java錯誤: Must qualify the allocation with an enclosing instance of type

錯誤:

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

代碼:
public class Test1 {
	int x = 0;
	public static void main(String args[]){
		new A();
	}
	class A{
		public A(){
			System.out.println(x);
		}
	}
}

爲什麼會有錯誤呢?

我們都知道,在執行main()函數時Test1類還沒有生成,而A是內部類,在生成內部類的時候必須首先生成外部類。

所以問題的解決方式有兩種:

1.將class A改爲static class A,並把int x = 0;改爲static int x = 0;

這是根據編輯器提示錯誤改的,靜態方法不能調用非靜態方法或類、屬性

2.將生成A的代碼更改如下

new Test1().new Test1a();
全部代碼:

public class Test1 {
	int x = 0;
	public static void main(String args[]){
		//new Test1a();
		new Test1().new Test1a();
	}
	class Test1a{
		public Test1a(){
			System.out.println(x);
		}
	}
}

如此即可。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章