Le byte -Java8 core real - Interface default method

JAVA8 has been released for a long time, is the most important release since after java5 (published in 2004) Oracle released. Including the new features of the language, compiler, libraries, tools, and many other aspects of the JVM, for domestic and foreign Internet companies, Java8 is the future trend of technological development. Here mainly on the development of several new features in the core. (The main characteristics of the new interpretation of the concept, syntax definition, simple code demonstrates the advantages and disadvantages analysis, preparation of project practical aspects).

First, the core features at a glance

17148270-d773e66eeb7c797d.png
1559024533089.png

Second, the interface default method

17148270-f135aa937590b89d.png
1559024806819.png

When registration site, we will use the default picture after registration website, usually after the application is installed successfully provides a default icon, through the purchase of goods for payment in electricity's website, we will set common shipping address as the default address, life seems to have a lot of scenes default one said. Java8 start, there are also the default word appears here for the original function interface that extends the interface Java8, and the default method to provide support.

concept

From Java8 start program allows the method comprising the interface with the particular implementation, use default modification, such a method is the default method. Default method can add a plurality of interface, and the interface provides many Java8 corresponding to the default method.

grammar

Java8 interfaces may include implementation, modification requires the use of default, such a method called the default method. The default method implemented in the interface must be provided, it can be rewritten as needed in the implementation class. The default method can only be invoked in the implementation class or by implementing the class object. The following form:

    public interface IMathOperation {
        /**
         * 定义接口默认方法 支持方法形参
         */
        default void print(){
            System.out.println("数值运算基本接口默认打印方法。。。");
        }
    }

Simple to use

  • Interface definition
    defined IMathOperation interface and provides a default print method
    public interface IMathOperation {
        /**
         * 定义接口默认方法 支持方法形参
         */
        default void print(){
            System.out.println("这是数值运算基本接口。。。");
        }
        /**
         * 整数加法运算方法
         * @param a
         * @param b
         * @return
         */
        public int add(int a,int b);
    }
  • Subclasses implement
    defined interfaces MathOperationImpl subclass implementation IMathOperation
17148270-7e07b4d285e93aa0.png
1559025070169.png
子类在实现时,按需重写接口默认方法
17148270-68ae6585aad9b42c.png
1559025140599.png
    public class MathOperationImpl implements  IMathOperation {
        @Override
        public int add(int a, int b) {
            // 子类中可以直接调用父类接口默认方法
            IMathOperation.super.print();
            // 调用父类静态默认方法
            IMathOperation.version();
            return a+b;
        }
    }

Multiple default method

使用Java8开发应用程序,子类实现多个接口时,对于接口默认方法定义允许定义多个默认方法,并且接口默认方法可能会出现同名情况,此时对于子类在实现或者调用时通常遵循以下原则:

A method for the highest priority class

2. If the first can not be determined, then the higher priority sub-interface: function signature is the same, the interface has a default priority choose the most specific method of implementation, that is, if B inherits A, then B is even more specific than A

Sample code is as follows:

    /**
     * 定义手机接口  提供默认info方法
     */
    public interface Phone {
        default void info(){
            System.out.println("这是一部手机");
        }
    }
    
    /**
     * 定义MiPhone子接口 并继承 Phone 父接口 同时也提供info方法
     */
    public interface MiPhone extends Phone{
        default void info(){
            System.out.println("这是一部小米手机");
        }
    }
    
    /**
     * 实现 Phone MiPhone 接口
     */
    public class M2sPhone implements Phone,MiPhone {
    
        public static void main(String[] args) {
            new M2sPhone().info();
        }
    }
    ```
    打印结果: 
    这是一部小米手机

# 三、接口静态方法

    接口中除了允许定义多个默认方法之外,Java8也允许在接口中定义多个静态方法,静态方法即通过static 修饰的方法。接口中静态方法也必须提供实现,提供了可以直接通过接口调用方法的方式。
public interface IMathOperation {
    /**
     * 定义接口默认方法 支持方法形参
     */
    default void print(){
        System.out.println("这是数值运算基本接口。。。");
    }
    
     /**
     * 定义静态默认方法
     */
    static void version(){
        System.out.println("这是1.0版简易计算器");
    }    
}
    接口中的静态方法只能通过接口本身去调用,类似于 Class 中的静态方法,不存在默认方法中的多继承问题,静态方法并不能在实现类中被覆写,实现类中可以声明相同的方法,但这两个方法之间除了名字相同,并没有 Override 关系。


# 四、接口默认方法实战

##网站活跃TOP3用户遍历

    这里以博客网站举例,比如统计每个月网站前三活跃用户(按用户文章发表量评判),使用集合遍历操作来使用接口默认方法,对于测试数据如下:

    uList=  new ArrayList<>();
    uList.add(new UserDto(35,"zs","[email protected]",800,"lv4"));
    uList.add(new UserDto(60,"js_li","[email protected]",500,"lv3"));
    uList.add(new UserDto(78,"fc_007","[email protected]",260,"lv2"));

- 增强for实现

得到统计集合数据后,最简单的方式使用增强for实现,也是java8之前常用的方式。

    System.out.println("----------集合遍历-->原始遍历方法---------");
    for(UserDto u:uList){
        System.out.println(u);
    }

- 自定义接口默认方法 
/**
 * @Version 1.0
 * 定义MyList 接口 并提供myForeach 默认方法
 */
public interface MyList<T> {
    /**
     * 定义接口默认方法
     * @param t
     */
   default public  void myForeach(List<T> t){
       for(Object o:t){
           System.out.println(o);
       }
   }
}

/**
 * @Version 1.0
 * 定义MyArrayList 子类  实现MyList 接口,继承ArrayList
 */
public class MyArrayList<T> extends ArrayList<T> implements   MyList<T> {
    
}

/**
  执行遍历
*/
System.out.println("----------集合遍历-->自定义接口默认方法---------");
// 使用自定义的接口默认方法实现集合元素遍历
uList.myForeach(uList);
- 使用增强的Iterable接口默认方法


System.out.println("----------集合遍历-->增强的List接口默认方法---------");
uList.forEach(new Consumer<UserDto>() {
@Override
public void accept(UserDto userDto) {
    System.out.println(userDto);
        }
    });
}   
## 网站活跃TOP3用户排序

这里以博客网站举例,比如统计每个月网站前三活跃用户(按用户文章发表量评判),使用集合排序操作来使用接口默认方法,对于测试数据如下:

- Collections.sort  工具类方法实现排序

    System.out.println("--------Collections.sort 实现按文章发表量排序---------");
            Collections.sort(uList, new Comparator<UserDto>() {
                @Override
                public int compare(UserDto o1, UserDto o2) {
                    return o1.getTotal()-o2.getTotal();
                }
            });
    uList.forEach(System.out::println);

- 增强的List接口默认sort方法
  借助Java8增强的List接口默认Sort方法实现集合排序操作


System.out.println("--------集合默认sort方法实现按文章发表量排序---------");
        uList.sort(new Comparator<UserDto>() {
            @Override
            public int compare(UserDto o1, UserDto o2) {
                return o1.getTotal()-o2.getTotal();
            }
        });
uList.forEach(System.out::println);
- Stream流sorted 方法实现排序(这里先做了解!)
  Stream流提供了针对集合的多种操作,这里借助Stream的sorted实现集合元素排序操作,后续会对Stream做详细介绍。


System.out.println("--------Stream实现按文章发表量排序---------");
       List<UserDto> result= uList.stream().sorted(new Comparator<UserDto>() {
            @Override
            public int compare(UserDto o1, UserDto o2) {
                return o1.getTotal()-o2.getTotal();
            }
        }).collect(Collectors.toList());
result.forEach(System.out::println);
# 五、接口默认方法与静态方法的优势

- 接口的兼容性得到解决
    使用接口编程的好处是,开发是面向抽象而不再是面向具体来编程,使得程序变得很灵活,缺陷是,当需要修改接口时候,此时对应实现该接口的类需要全部修改,举个例子, java 8 之前对于我们常用的集合框架没有 foreach 方法,通常能想到的解决办法是在JDK里给相关的接口添加新的方法及实现。从Java8开始,引入了接口默认方法,这样的好处也是很明显的,首先解决了Java8以前版本接口兼容性问题,同时对于我们以后的程序开发,也可以在接口子类中直接使用接口默认方法,而不再需要再各个子类中各自实现响应接口方法。
- 子类在实现接口方法时灵活度更高 
    子类在实现接口时,可以按需重写,不在向Java8以前接口方法必须全部实现,同时接口默认方法可以在子类中直接进行调用,灵活度比较高。
- 开发中避免大量工具类创建
    接口中引入静态方法,对于原有项目开发中出现大量的工具类大量静态方法的代码便可以迁移到接口中定义与实现,省去大量工具类的创建。
- 提升了对Lambda表达式的支持 
    Lambda 是针对只有一个抽象方法的接口来说的,接口中引入接口默认方法与静态方法,在对接口这些方法进行调用时,可以引入Lambda表达式简化了原有代码的书写形式,使得代码变得更加简洁。

乐字节原创,转载请注明出处和作者,
请继续关注乐字节,Java8更多核心特性会继续分享

Guess you like

Origin blog.csdn.net/weixin_33828101/article/details/90960793
Recommended