|NO.Z.00080|——————————|BigDataEnd|——|Java&特殊类.V08|——|Java.v08|回调模式|概念|

一、回调模式的概念
### --- 回调模式的概念

~~~     ——>        回调模式是指——如果一个方法的参数是接口类型,则在调用该方法时,
~~~     ——>        需要创建并传递一个实现此接口类型的对象;
~~~     ——>        而该方法在运行时会调用到参数对象中所实现的方法(接口中定义的)。
二、编程代码
package com.yanqi.task10;

public interface AnonymousInterface {
    // 自定义抽象方法
    public abstract void show();
}
三、编程代码
package com.yanqi.task10;

public class AnonymousInterfaceImpl implements AnonymousInterface {
    @Override
    public void show() {
        System.out.println("这里是接口的实现类!");
    }
}
四、编程代码
package com.yanqi.task10;

public class AnonymousInterfaceTest {

    // 假设已有下面的方法,请问如何调用下面的方法?
    // AnonymousInterface ai = new AnonymousInterfaceImpl();
    // 接口类型的引用指向实现类型的对象,形成了多态
    public static void test(AnonymousInterface ai) {
        // 编译阶段调用父类版本,运行调用实现类重写的版本
        ai.show();
    }

    public static void main(String[] args) {

        //AnonymousInterfaceTest.test(new AnonymousInterface()); // Error:接口不能实例化
        AnonymousInterfaceTest.test(new AnonymousInterfaceImpl());

        System.out.println("---------------------------------------------------------------");
        // 使用匿名内部类的语法格式来得到接口类型的引用,格式为:接口/父类类型 引用变量名 = new 接口/父类类型() { 方法的重写 };
        AnonymousInterface ait = new AnonymousInterface() {
            @Override
            public void show() {
                System.out.println("匿名内部类就是这么玩的,虽然你很抽象!");
            }
        };

        // 从Java8开始提出新特性lamda表达式可以简化上述代码,格式为:(参数列表) -> {方法体}
        AnonymousInterface ait2 = () -> System.out.println("lamda表达式原来是如此简单!");
        AnonymousInterfaceTest.test(ait2);
    }
}
五、编译打印
D:\JAVA\jdk-11.0.2\bin\java.exe "-javaagent:D:\IntelliJIDEA\IntelliJ IDEA 2019.3.3\lib\idea_rt.jar=54237:D:\IntelliJIDEA\IntelliJ IDEA 2019.3.3\bin" -Dfile.encoding=UTF-8 -classpath E:\NO.Z.10000——javaproject\NO.H.00001.javase\javase\out\production\javase com.yanqi.task10.AnonymousInterfaceTest
这里是接口的实现类!
---------------------------------------------------------------
lamda表达式原来是如此简单!

Process finished with exit code 0

 
 
 
 
 
 
 
 
 

Walter Savage Landor:strove with none,for none was worth my strife.Nature I loved and, next to Nature, Art:I warm'd both hands before the fire of life.It sinks, and I am ready to depart
                                                                                                                                                   ——W.S.Landor

 

 

posted on   yanqi_vip  阅读(21)  评论(0编辑  收藏  举报

相关博文:
阅读排行:
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
· DeepSeek 开源周回顾「GitHub 热点速览」
< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

导航

统计

点击右上角即可分享
微信分享提示