匿名内部类

  

 1 public class Parcel{
 2    public Contents contents() {
 3        return new Contents() {
 4          private int i = 11;
 5          public int value() {return i; }
 6      }
 7   }
 8 
 9   public static void main(String[] args)
10   {
11      Parcel p = new Parcel();
12      Contents c = p.contents();
13   }
14 
15 }

  上面便是一个匿名内部类的例子。在该例子中,contents方法将返回值的生成与表示这个返回值的类的定义结合在一起!另外,这个类是匿名的,它没有名字。

这种奇怪的语法指的是:"创建一个继承自Contents的匿名类的对象。"其相当于如下代码:

 

 1 public class Parcel {
 2    class MyContents implements Contents{
 3      private int i = 11;
 4      public  int value(){return i;}
 5    }
 6     public Contents contents() { return new MyContents();}
 7     public static void main(String[] args)
 8     {
 9         Parcel p = new Parcel();
10         Contents c = p.contents();
11     }
12 
13 }

 

 

 

 

 

 

 


 

 

posted @ 2013-04-11 23:13  mo_suyi  阅读(273)  评论(0编辑  收藏  举报