zoukankan      html  css  js  c++  java
  • 接口的匿名实现

           匿名类是不能有名称的类,所以没办法引用它们。必须在创建时,作为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. 我相信我们成为怎样的人是我们自己的选择。没有人会来拯救你,你必须要自己拯救自己。
  • 相关阅读:
    LVS-三种负载均衡方式比较
    keepalived和heartbeat区别
    vmware-question
    SQL Server MYSQL 检查点的好处
    MYSQL 引擎的情况
    MYSQL 关闭服务的过程
    SQL Server 行的删除与修改-------------(未完待续P222 deep SQL Server 222 )
    SQL Server一些重要视图 1
    SQL Server 查看数据页面
    SQL Server 向堆表中插入数据的过程
  • 原文地址:https://www.cnblogs.com/caroline/p/2390579.html
Copyright © 2011-2022 走看看