方法应用的基本介绍。方法引用_通过对象名字引用对象方法

方法引用的基本介绍

首先我们先来定义一个打印的接口


public class PrintableImpl {
public static void PrintString(Printable printable){
printable.pring("HelloWorld");
}

public static void main(String[] args) {
PrintString(System.out::println);
}
}

然后来实现这个接口,我们来创建一个main方法来调用一下

  运行结果:

 

 

来分析一下:

  Lambda表达式目的,打印参数传递字符串,把参数s传递给了System.out对象,调用out对象中的方法prin对字符串进行输出

  注意:

    System.out对象也是存在的

    prin对象也是存在的

    所以我们可以优化Lambda表达式

    我们可以使用Sysytem.out方法直接引用(调用)prin方法

public class PrintableImpl {
public static void PrintString(Printable printable){
printable.pring("HelloWorld");
}

public static void main(String[] args) {
PrintString(System.out::println);
}
}
  PrintString(System.out::println);

这样简化了Lambda表达式

 

方法引用_通过对象名字引用对象方法

  那么我们创建一个成员方法,传递字符串,把字符串按照大小输出

  

public class PrintableImpl {
public static void prinUpper(String str){
System.out.println(str.toUpperCase());
}

public static void aa(Printable printable){
printable.pring("nihao");
}

public static void main(String[] args) {
aa(PrintableImpl::prinUpper);
}
}

然后我们在创建一个函数式接口子在写一个接口的实现类,实现了接口之后然后在创建main方法

调用方法转递转大写的方法传输人参数输出,看运行结果:

  

 

 

        aa(PrintableImpl::prinUpper);

这里同时使用了方法引用



posted @   一位程序袁  阅读(52)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
点击右上角即可分享
微信分享提示