public class Parce { class Contents {
private Contents()
{
}
private int i = 11; public int value() { return i; } } class Destination { private String label; private Destination(String label) { this.label = label; } public String readLabel() { return this.label; } } /** * * @return 因为构造器私有化,只有这个方法可以返回本类实例。 */ public Contents getContents() { return new Contents(); } /** * @param s * @return 因为构造器私有化,只有这个方法可以返回本类实例。 */ public Destination getDestination(String s) { return new Destination(s); } public void ship(String s) { Contents contents = getContents(); Destination destination = getDestination(s); System.out.println(destination.readLabel()); } /** * @param args */ public static void main(String[] args) { Parce parce = new Parce(); parce.ship("干掉你哦"); Parce.Contents contents = parce.getContents(); Parce.Destination destination = parce.getDestination("傻逼了吧"); } }
内部类拥有其外围类的所有元素的访问权。
使用.this和.new:
如果需要生成对外部类对象的引用,可以使用外部类的名字加上.this即可。如果要创建某某个内部类对象,可以外部类对象加上.new语法。
1 public class DotThis 2 { 3 4 public class Inner 5 { 6 public DotThis outer() 7 { 8 return DotThis.this; 9 } 10 } 11 public Inner inner() 12 { 13 return new Inner(); 14 } 15 public void f() 16 { 17 System.out.println("DotThis.f()调用了"); 18 } 19 /** 20 * @param args 21 */ 22 public static void main(String[] args) 23 { 24 DotThis dotThis = new DotThis(); 25 DotThis.Inner inner = dotThis.inner(); 26 inner.outer().f(); 27 } 28 29 }
25行可以用DotThis.Inner inner = dotThis.new Inner();代替.
内部类与向上转型(与回调函数很相似)
1 //Contents.java 2 public interface Contents 3 { 4 int value(); 5 } 6 //Destination.java 7 public interface Destination 8 { 9 String readLabel(); 10 } 11 //Parce2.java 12 public class Parce2 13 { 14 private class PContents implements Contents 15 { 16 private int i = 11; 17 18 @Override 19 public int value() 20 { 21 return i; 22 } 23 } 24 25 private class PDestination implements Destination 26 { 27 private String label; 28 29 private PDestination(String label) 30 { 31 this.label = label; 32 } 33 34 @Override 35 public String readLabel() 36 { 37 return this.label; 38 } 39 40 } 41 42 /** 43 * 44 * @return 因为构造器私有化,只有这个方法可以返回本类实例。 45 */ 46 public Contents getContents() 47 { 48 return new PContents(); 49 } 50 51 /** 52 * @param s 53 * @return 因为构造器私有化,只有这个方法可以返回本类实例。 54 */ 55 public Destination getDestination(String s) 56 { 57 return new PDestination(s); 58 } 59 60 /** 61 * @param args 62 */ 63 public static void main(String[] args) 64 { 65 Parce2 parce = new Parce2(); 66 Contents contents = parce.getContents();//子类对象指向父类(继承的接口)对象,称为向上转型 67 Destination destination = parce.getDestination("呵呵"); 68 69 } 70 71 }
内部类PContents是private,除了Parce2,没人能访问它。实际上,甚至不能向下转型成private内部类(或protected内部类,除非继承自它的子类),因为不能访问其名字。这样就能完全隐藏了细节。
原文:http://www.cnblogs.com/linlin-meimei/p/4359638.html