zoukankan      html  css  js  c++  java
  • 匿名内部类

    • 普通匿名内部类
     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  
  • 相关阅读:
    SCAU 9504 面试
    SCAU 9503 懒人选座位
    SCAU 8628 相亲
    SCAU 10691 ACM 光环
    SCAU 8626 原子量计数
    SCAU 10674 等差对
    HDU ACM 1048 The Hardest Problem Ever (水题)
    SCAU 9502 ARDF
    SCAU 10686 DeathGod不知道的事情
    SCAU 8629 热身游戏(高精度)
  • 原文地址:https://www.cnblogs.com/vi3nty/p/7600399.html
Copyright © 2011-2022 走看看