Java8系列之初识
前言:终于有机会在工作中使用高版本的Java8,但是一直没有对java8中添加的新特性进一步了解过,所以趁着这个机会学习一下,能够在编程中熟练的使用。
一、接口的改变
我们知道,在java8版本以前,接口中只能定义静态常量和抽象方法,但是在java8添加了默认方法,也叫扩展方法;
- public interface DefaultInterface {
- //默认是public static final,也只能是
- public static final int count = 0;
- //抽象方法
- void add();
- //默认方法==>扩展方法
- default int add(int x, int y) {
- return x + y;
- }
- }
这样,实现类不必实现默认方法,只需实现抽象方法,使用时直接调用接口中的方法。(好像和流式的api引入有关)
- public class DefaultImpl implements DefaultInterface {
- @Override public void add() {
- System.out.println("我是抽象方法的实现");
- }
- public static void main(String[] args) {
- DefaultInterface di = new DefaultImpl();
- di.add();
- di.add(12, 3);
- }
- }
posted on 2017-10-22 23:55 menghuanzhiwuhen 阅读(...) 评论(...) 编辑 收藏