能够将一个类的定义放在另外一个类的定义内部,这就是内部类。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()); } }