- 匿名内部类
用于创建一个临时的实现子类,而不用单独再写一个实现类。
比如有个抽象类
public abstract class Student {
protected void study(int a) {
}
}
可以通过在方法中,实现该抽象类,如下
public class StudentA {
public static void main(String[] args) {
Student student = new Student() {
@Override
protected void study(int a) {
System.out.println("a=" + a);
}
};
student.study(10);
}
}
这样可以不用单独写一个实现类,而是需要时再去实现。
- 用lambda表达式简化匿名内部类
如果接口中,有且仅有一个待实现的方法,我们可以用lambda表达式去简化匿名内部类的实现。
比如接口如下:
public interface Student {
void study(int a);
}
实现可以写成
public class StudentA {
public static void main(String[] args) {
Student student = (int a) ->
System.out.println("a=" + a);
student.study(10);
}
}
需要记住:
- lambda表达式简写只支持接口,不支持抽象类
- 只有一个待实现的方法,其他方法需要有默认实现方式,如加default修饰