public class InnerClass { class Content { private int i; public int getVlaue() { return i; } } class Description { private String lable; Description(String lab) { this.lable = lab; } public String readLable() { return lable; } } public Content getContentInstance() { return new Content(); } public Description getDescriptionIntance(String lable) { return new Description(lable); } public void ship(String lable) { Content content = getContentInstance(); Description description = getDescriptionIntance(lable); System.out.println(description.readLable()); System.out.println(description.readLable()); } /** * 在建立外部类对象前,是不能够建立内部类对象的,由于内部类对象会暗暗的链接到外部类对象之上。<p> * 若是你想经过外围类对象建立内部类对象 以前已经说过最简单的方法是在外围类声明一个方法指向其内部类的对象。另外一种更加简单的作法 * JAVA支持经过外围类对象.new 语法表达一个外围类对象的引用 * @param args */ public static void main(String[] args) { InnerClass parcle2 = new InnerClass(); InnerClass.Content c = parcle2.new Content(); System.out.println(c.getVlaue()); // parcle2.ship("hi"); // InnerClass.Content c = parcle2.getContentInstance();// 若是想在外部类的非静态方法以外的任意位置访问某个内部类的对象,那么必须经过OutClass.xx InnerClass.Description d = parcle2.new Description("hello"); System.out.println(d.readLable()); // InnerClass.Description d = parcle2.getDescriptionIntance("hello"); } }
使用.this,.newide
.this 表达的是在内部类对象域内 经过外部类.this 指向了一个在内部类指向外围类对象引用的关系。只有这样能够访问外围类对象的属性与方法this
.new表达的是与.this方向相反 当在外围类做用域上 想建立内部类对象 以前通用的作法是 在外围类建立一个指向内部类的引用来建立内部类,但有一种更加快捷的方式spa
直接外围类.new 就能够表达一个外围类对象引用 。这里必须强调一点 在拥有外部类对象以前是不可能建立外围类对象的,由于内部类对象会暗暗的链接到建立他的外围类对象上code
改变一下上面的内部类例子对象
public class InnerClass { class Content { private int i; public int getVlaue() { return i; } } class Description { private String lable; Description(String lab) { this.lable = lab; } public String readLable() { return lable; } } public Content getContentInstance() { return new Content(); } public Description getDescriptionIntance(String lable) { return new Description(lable); } public void ship(String lable) { Content content = getContentInstance(); Description description = getDescriptionIntance(lable); System.out.println(description.readLable()); System.out.println(description.readLable()); } /** * 在建立外部类对象前,是不能够建立内部类对象的,由于内部类对象会暗暗的链接到外部类对象之上。<p> * 若是你想经过外围类对象建立内部类对象 以前已经说过最简单的方法是在外围类声明一个方法指向其内部类的对象。另外一种更加简单的作法 * JAVA支持经过外围类对象.new 语法表达一个外围类对象的引用 * @param args */ public static void main(String[] args) { InnerClass parcle2 = new InnerClass(); InnerClass.Content c = parcle2.new Content(); System.out.println(c.getVlaue()); // parcle2.ship("hi"); // InnerClass.Content c = parcle2.getContentInstance();// 若是想在外部类的非静态方法以外的任意位置访问某个内部类的对象,那么必须经过OutClass.xx InnerClass.Description d = parcle2.new Description("hello"); System.out.println(d.readLable()); // InnerClass.Description d = parcle2.getDescriptionIntance("hello"); } }