JAVA基础 | 方法与构造方法的引用 + Lambda表达式实例(210119)

JAVA基础 | 方法与构造方法的引用 + Lambda表达式实例(210119)

【1.方法引用】

package test;

//方法的引用 (使用"::"去引用)

@SuppressWarnings("hiding")
interface A<String,Integer>{
	Integer a(String s);  //抽象方法未被类实现,但通过引用实现了
}

public class Test_1 {
	public static void main(String[] args) {
		A<String,Integer> a=Integer::valueOf; //抽象方法参数要和被引用方法一致
		Integer i=a.a("5");
		System.out.println(i);
		A<String,Integer> b=Integer::parseInt;
		try {
		//Integer j=b.a("a"); 
		Integer j=b.a("10");   //必须是数字型的字符串 否则报错
		System.out.println(j);
		}
		catch(Exception e) {
			e.printStackTrace();
		}
	}
}
//运行结果:
5
10

【2.构造方法引用】

package test;
//构造方法的引用 (使用"::"进行引用)
interface B<T extends Fruit>{
	T b(String a,String b);
}

class Fruit{
	private String name;
	private String color;
	public Fruit(String n,String c) {
		name=n;
		color=c;
		System.out.println(name+":"+color);
	}
	public Fruit() {}
	public void get() {
		System.out.println("随便写的");
	}
}

public class Test_2 {
	public static void main(String[] args) {
		B<Fruit> b=Fruit::new;
		Fruit f=b.b("apple", "red"); //方法引用规则是根据参数去匹配的
		f.get();
	}
}
//运行结果:
apple:red
随便写的

【3.Lambda表达式】

package test;

//Lambda表达式的基础实例

interface AA{
	public void print(String s) ;
}

interface BB{
	public int print(int s) ;
}

public class Test_3{
	public static void main(String args[]) {
		AA a=(t)->System.out.println(t);	//Lambda表达式的值要与接口方法中的参数一致
		a.print("???");
		int num=10;
		BB b=(t)->Integer.valueOf(t+num);   //Lambda表达式的值要与接口方法的返回类型一致
		System.out.println(b.print(5));
	}
}
//运行结果:
???
15

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值