一:定義在成員位置上
1,內部類可以直接訪問外部類中的成員,包括私有.
之所以可以直接訪問外部類的成員,是因爲內部類中持有一個外部類的引用,格式爲:外部類名.this
2,外部類要訪問內部類,必須建立內部類的對象.
class Outer
{
private int x =3;
class Inner
{
int x=4;
void function(){
int x=5;
System.out.println("inner:"+x);//the output is 5
System.out.println("inner:"+this.x);//the output is 4
System.out.println("inner:"+Outer.x);//the output is 3;
}
}
void method(){
Inner in =new Inner();
in.function();
}
}
1,內部類的訪問格式:外部類名.內部類名 變量名=外部類對象.內部類對象 Outer.Inner in=new Outer().new Inner(); 條件: 內部類定義在外部類的成員位置上,爲非私有.
2,可以通過private修飾符將內部類在外部類中進行封裝,當內部類被static修飾後,只能直接訪問外部類中的static成員,出現了訪問侷限. 在外部其他類中,訪問static修飾的內部類的未被static修飾的成員: new Outer.Inner().function(); 在外部其他類中,直接訪問static修飾的內部類的也被static修飾的成員: Outer.Inner.function();
class Outer { private static int x=3; static class Inner { static void function(){ System.out.println("inner:"+x); } } } class InnerClassDemo { public static void main(String[] args){ new Outer.Inner().function();//when the function is not static Outer.Inner.function();//when the inner function is static } }
* There is one thing that must be careful : 當內部類中有static修飾的成員時,內部類必須也爲被static修飾的.
* when to use it ? 當描述事物時,如果事物的內部還有事物,就把這個事物描述爲內部類,這樣,內部事物可以不用創建外部類的對象同時就可以使用外部事物的內容.
二:內部類定義在局部時: 1,不可以被成員修飾符所修飾, 2,可以直接訪問外部類中的成員,因爲它持有外部類中的引用-Outer.this,但是不可以訪問它所在的局部中的變量,非要訪問時,應該將該局部變量用final修飾.
The example codes :
class Outer {
int x=3;
void method(){
final int y=4;
//①
class Inner
{
void function(){
System.out.println(y);
}
}
new Inner().function();//this sentence must be there ,can't be put at ①
}
}
class TestOuter
{
public static void main(String[] args){
new Outer.method();
}
}
三,匿名內部類:
1,其實是內部類的簡寫形式
2,必須繼承一個類,或者實現一個藉口.
3,格式:new 父類或者接口(){定義子類內容,如果繼承的爲抽象類或接口,則要重寫裏面的抽象方法}
4,其實匿名內部類就是一個匿名子類對象,而且這個對象有點胖,即加了{}這個內容.
5,原則: 匿名內部類中定義的方法最好不要超過3個.因爲定義匿名內部類的目的通常是爲了簡便調用.
abstract class AbsDemo { abstract void show(); } class Outer { int x=3; public void function(){ new AbsDemo(){ void show(){ System.out.println("x="+x); } void show2(){ System.out.println("haa"); } }.show();//you can also invoke the show2 method,which is new definited,but you can only choose one of them,because 匿名對象只能調用一次某個方法. } //same as: AbsDemo d=new Inner();which is 多態 AbsDemo d=new AbsDemo(){ void show(){ System.out.println("x="+x); } void show2(){ System.out.println("haa"); } }; //now you can do like this : d.show();//right; d.show2();//wrong; }