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


之前看內部類的時候沒發現這個問題,今天寫代碼的時候遇到,寫個最簡單的例子:

下面這一段代碼

紅色的部分就是編譯報錯:

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

根據提示,沒有可以訪問的實例Outer,必須分配一個合適的外部類實例以訪問內部類。

正確的方式可以是:

public class Outer {
	private int i = 10;
	class Inner{
		public void seeOuter(){
			System.out.println(i);
		}
	}
	public static void main(String[] args) {
		Outer out = new Outer();
		Inner in = out.new Inner();
		in.seeOuter();
	}
}

或者:

public class Outer {
	private int i = 10;
	static class Inner{
		public void seeOuter(){
			// 靜態內部類不能直接訪問外部類的非靜態成員,但可以通過 new 外部類().成員 的方式訪問 
			//System.out.println(i);這句話編譯不過
			System.out.println(new Outer().i);
		}
	}
	
	public static void main(String[] args) {
		Inner in = new Inner();
		in.seeOuter();
	}
}

關於內部類

  • 依然是一個獨立的類,在編譯之后會內部類會被編譯成獨立的.class文件,但是前面冠以外部類的類命和$符號。
  • 內部類不能用普通的方式訪問。內部類是外部類的一個成員,因此內部類可以自由地訪問外部類的成員變量,無論是否是private的。
  • 成員內部類內不允許有任何靜態聲明!
  • 能夠訪問成員內部類的唯一途徑就是通過外部類的對象!

有關內部類具體可參考
http://blog.csdn.net/ft305977550/article/details/8350708

僅僅記錄編程中遇到的問題。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM