java 自我知识总结 (十九)lamdba表达式和内部类

一)lambda表达式 就是对匿名内部类的一种简化写法


public class Test2 {
public int a ;
public static void main(String[] args) {
/*Animal a = new Animal(){
@Override
public void eat() {
System.out.println("这是一头牛");
}
};
a.eat();*/
// lambda表达式 java8 的新特性
Animal a = ()‐>{System.out.println("这是一头牛");};
a.eat();
}
}
lambda 表达式特点:
1) 必须是函数式接口 ?
函数式接口:接口中有且只有一个抽象方法。
@FunctionalInterface
public interface Animal {
public abstract void eat();
//void sleep(int i);
}
2) 参数类型可以省略 @FunctionalInterface 可以校验函数式接口。
@FunctionalInterface
public interface Animal {
public abstract String eat(int a ,String b);
}
Animal a = (int c ,String b)‐>{return null;};
例子: 在方法体使用对应的参数
Animal a = ( c , b)‐>{
b ="一头牛";
System.out.println(b+"吃了"+ c+"斤");
return null;
};
a.eat(100, "黄牛");
3)函数体重如果只有一句,函数体的大括号可以省略,如果有返回值,return也要省略
Animal a = ( c , b)‐> b;
4) 抽象类不能使用lambda 表达式
@FunctionalInterface
public abstract class Person {
abstract void test();
}
练习:
interface Math{
int add(int a ,int b );
}
使用lambda表达式 实现上面的类。




二)内部类: 可以放在函数中,也可以放在类中。
放在类中就是类的成员。 同样可以访问 类中其他成员
类中也可以存在接口和抽象类。 内部接口。
package com.uplooking;
public class Cat {
String name;
int age;
class LittleCat{
void test(){
System.out.println(name+age);
}
}
}
会发现生成了两个class文件:Cat$LittleCat.class Cat.class
例子:
public static void main(String[] args) {
Cat c = new Cat();
c.age = 7 ;
c.name = "tom";
LittleCat c2 =c.new LittleCat();
c2.test();
}
public class Cat {
String name;
int age;
static String color;
static class LittleCat{
void test(){
System.out.println(color);
}
}
}
静态内部类:
创建对象方式。
Cat.color = "小老虎";
Cat.LittleCat l = new Cat.LittleCat();
l.test();
例子: 当内部类与主类中的属性冲突时;
public class Cat {
String name;
int age;
static String color;
class LittleCat{
String name;
void test(){
System.out.println( Cat.this.name); // 调用的是 全局的name
}
}
}
例子: 内部类 放在方法里面
package com.uplooking;
public class Cat {
String name;
int age;
static String color;
void test(){
class LittleCat{
String name;
void test(){
System.out.println(name);
}
}
LittleCat cat = new LittleCat();
cat.name = "aaa";
cat.test();
}
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值