內部類,即將一個類定義置於另一個類的定義之中。
public class Parcel1 {
class Contents{
private int i = 11;
public int value(){
return i;
}
}
public Contents cont(){
return new Contents();
}
class Destination{
private String label;
Destination(String whereTo){
label = whereTo;
}
String readLabel(){
return label;
}
}
public Destination dest(String la){
return new Destination(la);
}
public void ship(String dest){
Contents c = new Contents();
Destination d = new Destination(dest);
System.out.println(d.readLabel() + c.i);
}
public static void main(String[] args) {
// TODO Auto-generated method stub
Parcel1 p = new Parcel1();
p.ship("hahaha");
Parcel1.Contents a = p.cont();
Parcel1.Destination b = p.dest("lalala");
System.out.println(b.readLabel() + a.i);
}
}
上例中,Contents和Destination就是定義在Parcel1中的類。這裏稱Contents和Destination爲內部類,稱Parcel1爲外部類。特點:1.內部類可以自由地訪問外部類的成員變量;2.如果內部類被static修飾,即靜態的,那麼他只能訪問外部類的靜態變量。3.在外部類非static方法內部之外的任何地方(即static方法)生成內部類的一個對象,必須將那個對象的類型設爲“外部類.內部類”(如main中Parcel1.Contents a =
p.cont();以及ship中 Contents c = new Contents();)。例如cont()就是外部類的一個特殊方法,返回一個內部類的句柄。