【java】內部類

內部類:將一個類定義在另外一個類裏。對裏面的那個類就是內部類。java

訪問特色:函數

1.內部類能夠直接訪問外部類的成員,包括私有。之因此能夠直接訪問外部類中的成員,是由於內部類中持有了一個外部的引用,格式 外部類名.this
 外部類要訪問內部類,必須創建內部類對象。this

2.當內部類定義在外部類的成員位置上,並且爲非私有,能夠在外部類或者外部其餘類中直接創建內部類對象。
格式爲:外部類名.內部類名 變量名 = 外部類對象。內部類對象;
    Outer.Inter i1=new Outer().new Inter();spa

3.當內部類在成員位置上,就能夠被成員修飾符修飾。
       好比private:將內部類在外部類中進行封裝
    static:內部就具有了static的特性.
 當內部類被static修飾後,只能直接訪問外部類的static成員,出現了訪問的侷限性。
   在外部其餘類中,如何直接訪問static內部類的非靜態成員?
    new Outer.Inter().function();
  在外部其餘類中,如何直接訪問static內部類的靜態成員?
    Outer.Inter.function();
4.當內部類定義了靜態成員,該內部類必須是static的。當外部類的靜態方法訪問內部類時,內部類也必須是static的。對象

class Outer
{
	private int x=1;
	private int num=3;
	class Inter//內部類
	{
		int x=4;
		void function()
		{
			int x=6;
			System.out.println("i am  inter : "+num);
			System.out.println("inter x1 : "+Outer.this.x);//外部類名.this方式直接訪問外部類成員
			System.out.println("inter x2 : "+this.x);//訪問內部類成員
			Outer.this.show();//外部類名.this方式直接訪問外部類成員
		}
	}

	void show()
	{
		System.out.println(num);
	}
}


class  InterDemo
{
	public static void main(String[] args) 
	{
		Outer o1=new Outer();
		o1.show();
		Outer.Inter i1=new Outer().new Inter();//外部類要訪問內部類,必須創建內部類對象。
		i1.function();
	}
}

 

匿名內部類:
1.匿名內部類實際就是內部類的簡寫格式。
2.定義匿名內部類的前提:
  內部類必須是繼承一個類或者實現接口
3.匿名內部類的格式:
  new 父類或者接口(){定義子類的內容}
4.其實匿名內部類就是一個匿名子類對象。能夠理解爲帶內容的對象
5.匿名內部類中定義的方法最好不要超過3個blog

interface Inter
{
	void show(int a,int b);
	void func();
}
class Demo
{
	public static void main(String[] args)
	{
		//補足代碼;調用兩個函數,要求用匿名內部類
		Inter in = new Inter()
		{
			public void show(int a,int b)
			{
			
			}
			public void func()
			{
			
			}
		};

		in.show(4,5);
		in.func();
		
	}
}
相關文章
相關標籤/搜索