如何理解內部類

●將一個類定義在另一一個類的裏面,對裏面那個類就稱爲內部類(內置類,嵌套類)
●訪問特點:
內部類的訪問規則:

1,內部類可以直接訪問外部類中的成員,包括私有。
之所以可以直接訪間外部類中的成員,是因爲內部類中持有了一個外部類的引用,格式外部類名. this
2,外部類要訪問內部類,必須建立內部類對象。

●訪問格式:
1,當內部類定義在外部類的成員位置上,而且非私有,可以在外部其他類中。
可以直接建立內部類對象.
格式

外部類名.內部類名
變量名=外部類對象.內部類對象;
Outer . Inner in = new Outer () .new Inner () ;

2,當內部類在成員位置上,就可以被成員修飾符所修飾。
比如,private: 將內部類在外部類中進行封裝.
static:內部類就具備static的特性。
當內部類被static修飾後,只能直接訪問外部類中的static成員。出現了訪問侷限。

    	在外部其他類中,如何直接訪問static內部類的非靜態成員呢?
		new Outer. Inner() . function() ;

		在外部其他類中,如何直接訪間static內部類的靜態成員呢?
		Outer. Inner. function() ;

注意:當內部類中定義了靜態成員,該內部類必須是static的。I
當外部類中的靜態方法訪問內部類時,內部類也必須是static的。

class Outer
{
	private int x  = 3;
	
	class Inner//內部類
	{
		int x = 4;
		void  function()
		{
			int x= 6;
			System.out.println("inner :"+Outer.this.x);
			System.out.println("inner :"+this.x);
			System.out.println("inner :"+x);
		}
	}
	 void method()
	{
		Inner in = new Inner();
		in.function();
	}
	
	private static int y  = 3;
	static class Inner2//靜態內部類
	{
		static int y = 4;
		static void  function()
		{
			int y= 6;
			System.out.println("inner :"+Outer.y);
			System.out.println("inner :"+Inner2.y);
			System.out.println("inner :"+y);
		}
		void show()
		{
			System.out.println("在外部其他類中,如何直接訪問static內部類的非靜態成員");
		}
		void see()
		{
			// 靜態內部類不能直接訪問外部類的非靜態成員,但可以通過 new 外部類().成員 的方式訪問 
			//System.out.println(i);這句話編譯不過
			System.out.println(new Outer().x);
		}
	}
	
	
	
	static void method2()
	{
		Inner2.function();
	}
}
public class 面向對象09_01內部類 {
public static void main(String[] args) {
	Outer out = new Outer();
	out.method();
	System.out.println();
	
	//在外部其他類中,如何直接訪問static內部類的非靜態成員
	Outer. Inner2 in=new Outer. Inner2() ;
	in.show();
	//也就是
	new Outer. Inner2().show();
	System.out.println();
	
	//在外部其他類中,如何直接訪問static內部類的靜態成員
	Outer. Inner2 . function() ;
	System.out.println();
	
	Outer.method2();
	System.out.println();
	
	//直接訪問內部類中的成員。(面試可能會有)
	Outer.Inner inn = new Outer().new Inner();
	inn.function();
	
}
}

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