• 接口的匿名实现


           匿名类是不能有名称的类,所以没办法引用它们。必须在创建时,作为new语句的一部分来声明它们。 这就要采用另一种形式的new语句,如下所示: new <类或接口> <类的主体> 这种形式的new语句声明一个新的匿名类,它对一个给定的类进行扩展,或者实现一个给定的接口。它还创建那个类的一个新实例,并把它作为语句的结果而返回。要扩展的类和要实现的接口是new语句的操作数,后跟匿名类的主体。 如果匿名类对另一个类进行扩展,它的主体可以访问类的成员、覆盖它的方法等等,这和其他任何标准的类都是一样的。如果匿名类实现了一个接口,它的主体必须实现接口的方法。

    如下所示的例子:

    接口:

    1 package com.test.imp;
    2
    3 public interface Test {
    4
    5 public String hello();
    6
    7 }

    实现类:

     1 package com.test.imp;
    2
    3 public class Client {
    4
    5 public Test test;
    6
    7 public static void main(String[] args) {
    8 Client client = new Client();
    9 client.setTest(new Test() {
    10 public String hello() {
    11 System.out.println("匿名接口的实现");
    12 return null;
    13 }
    14 });
    15
    16 client.getTest().hello();
    17 }
    18
    19 public Test getTest() {
    20 return test;
    21 }
    22
    23 public void setTest(Test test) {
    24 this.test = test;
    25 }
    26
    27 }

    运行结果:

    匿名接口的实现

    另一个例子:(在Struts2的源码类-ContainerImpl.addInjectorsForMethods方法中就使用如下的例子)

     1 package com.test.imp;
    2
    3 public class Client {
    4
    5 public Test test;
    6
    7 public static void main(String[] args) {
    8 Client client = new Client();
    9 client.testImp(new Test() {
    10 public String hello() {
    11 System.out.println("调用了我。");
    12 return null;
    13 }
    14 });
    15 }
    16
    17 public Test getTest() {
    18 return test;
    19 }
    20
    21 public void setTest(Test test) {
    22 this.test = test;
    23 }
    24
    25 public void testImp(Test test) {
    26 // 在这里我要调用Test定义的Hello方法。
    27 test.hello();
    28 // 实现了动态的调用接口中的定义的方法,而没有使用
    29 // 接口的实现类,只使用了接口的匿名实现类
    30 }
    31
    32 }


    --待续

    I believe that we are who we choose to be. Nobody‘s going to come and save you, you‘ve got to save yourself. 我相信我们成为怎样的人是我们自己的选择。没有人会来拯救你,你必须要自己拯救自己。
  • 相关阅读:
    contentEditable
    Web开发工具(插件)收集
    用limit 传变量TO 存储过程解决方案(续)
    ASP.NET1.1和ASP.NET2.0中数据库连接字符串的不同设置
    按比例微缩图片的一段小小的JS代码
    研究下市场上有哪些软件项目/产品,哪些是值得做的?
    Ajax联动下拉框的实现例子
    C#装箱与拆箱
    在VS2005连接SQL2005时不允许远程连接
    联系我们
  • 原文地址:https://www.cnblogs.com/caroline/p/2390579.html
Copyright © 2020-2023  润新知