匿名内部类

  • 普通匿名内部类
 1 /*
 2 *普通匿名内部类
 3 */
 4 public class Parcel7{
 5     public Contents contents(){
 6         return new Contents(){
 7             private int i=11;
 8             public int value(){return i;}
 9         };
10     }
11     public static void main(String[] args){
12         Parcel7 p=new Parcel7();
13         Contents c=p.contents();
14     }
15 }

上例代码第5行,contents方法返回的应该是一个Contents对象。但这个返回值与类的定义结合在一起,即这个类是匿名的。5-9行代码进行“翻译”后如下所示

1 class MyContents implements Contents{
2     private int i=11;
3     public int value(){
4         return i;
5     }
6 }

  • 含参匿名内部类
 1 /*
 2 * 带有构造器的匿名内部类
 3 * */
 4 public class Parcel8 {
 5     public Wrapping wrapping(int x){
 6         return new Wrapping(x){//传递含参的构造器
 7             public int value(){
 8                 return super.value()*47;
 9             }
10         };
11     }
12 }
13 class Wrapping {
14     private int i;
15     public Wrapping(int x) {
16         i=x;
17     }
18     public int value(){
19         return i;
20     }
21 }
22  
原文地址:https://www.cnblogs.com/vi3nty/p/7600399.html