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  
  • 相关阅读:
    Python学习笔记 for windows 二
    Socket.io:有点意思
    MEAN Stack:创建RESTful web service
    在EC2上安装MEAN环境
    NodeJS:树的序列化
    NodeJS:树的反序列化
    NodeJS学习:爬虫小探补完计划
    NodeJS学习:爬虫小探
    依赖包bcrypt安装Issues
    Mongoose:Schema之路
  • 原文地址:https://www.cnblogs.com/xpang0/p/7600399.html
Copyright © 2011-2022 走看看