能夠將一個類的定義放在另外一個類的定義內部,這就是內部類。java
10.1建立內部類code
一、當咱們在ship()方法裏面使用內部類的時候,與使用普通類沒有什麼不一樣。對象
public class Parcel1 { class Contents { private int i = 11; public int value() { return i; } } class Destination { private String label; Destination (String whereTo) { label = whereTo; } String readLabel() { return label; } } public void ship (String dest) { Contents c = new Contents(); Destination d = new Destination(dest); System.out.println(c.value()); System.out.println(d.readLabel()); } public static void main(String [] args) { Parcel1 p = new Parcel1(); p.ship("Tasmania"); } }
二、外部類將有一個方法,該方法返回一個指向內部類的引用。若是想要從外部類的非靜態方法以外的任意位置建立某個內部類的對象,那麼必須具體指明這個對象的類型:ip
public class Parcel2 { class Contents { private int i = 11; public int value() { return i; } } class Destination { private String label; Destination (String whereTo) { label = whereTo; } String readLabel() { return label; } } public Destination to(String s) { return new Destination(s); } public Contents contents() { return new Contents(); } public void ship(String dest) { Contents c = contents(); Destination d = to(dest); System.out.println(d.readLabel()); } public static void main(String [] args) { Parcel2 p = new Parcel2(); p.ship("Tasmania"); Parcel2 q = new Parcel2(); Parcel2.Contents c = q.contents(); Parcel2.Destination d = q.to("xiao"); System.out.println(d.readLabel()); } }