详解Java8新特性之interface中的static方法和default方法

时间:2022-11-02 14:58:35

为什么要单独写个java8新特性,一个原因是我目前所在的公司用的是jdk8,并且框架中用了大量的java8的新特性,如上篇文章写到的stream方法进行过滤map集合。stream方法就是接口collection中的default方法。所以准备专门写写关于java8新特性的文章,虽然现在10已经发布了。但还是要认真的去了解下新版本的变化。

static方法

java8中为接口新增了一项功能:定义一个或者更多个静态方法。用法和普通的static方法一样。

代码示例

?
1
2
3
4
5
6
7
8
public interface interfacea {
  /**
   * 静态方法
   */
  static void showstatic() {
    system.out.println("interfacea++showstatic");
  }
}

测试

?
1
2
3
4
5
public class test {
  public static void main(string[] args) {
    interfacea.show();
  }
}

结果

interfacea++showstatic

注意,实现接口的类或者子接口不会继承接口中的静态方法

default方法

在接口中,增加default方法, 是为了既有的成千上万的java类库的类增加新的功能, 且不必对这些类重新进行设计。 比如, 只需在collection接口中

增加default stream stream(), 相应的set和list接口以及它们的子类都包含此的方法, 不必为每个子类都重新copy这个方法。

代码示例

实现单一接口,仅实现接口

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
public interface interfacea {
  /**
   * 静态方法
   */
  static void showstatic() {
    system.out.println("interfacea++showstatic");
  }
  /**
   * 默认方法
   */
  default void showdefault() {
    system.out.println("interfacea ++showdefault");
  }
}
/**先只实现这个接口
 * @author: curry
 * @date: 2018/7/31
 */
public class interfaceaimpl implements interfacea{
}

测试

?
1
2
3
4
5
6
public class test {
  public static void main(string[] args) {
    interfacea.showstatic();
    new interfaceaimpl().showdefault();
  }
}

结果

interfacea++showstatic
interfacea ++showdefault

如果接口中的默认方法不能满足某个实现类需要,那么实现类可以覆盖默认方法。

实现单一接口,重写接口中的default方法

?
1
2
3
4
5
6
7
8
9
public class interfaceaimpl implements interfacea{
  /**
   * 跟接口default方法一致,但不能再加default修饰符
   */
  @override
  public void showdefault(){
    system.out.println("interfaceaimpl++ defaultshow");
  }
}

测试

?
1
2
3
4
5
6
public class test {
  public static void main(string[] args) {
    interfacea.showstatic();
    new interfaceaimpl().showdefault();
  }
}

结果

interfacea++showstatic
interfaceaimpl++ defaultshow

实现多个接口,且接口中拥有相同的default方法和static方法

新创建个接口interfaceb

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
/**
 * @author: curry
 * @date: 2018/7/31
 */
public interface interfaceb {
  /**
   * 静态方法
   */
  static void showstatic() {
    system.out.println("interfaceb++showstatic");
  }
  /**
   * 默认方法
   */
  default void showdefault() {
    system.out.println("interfaceb ++showdefault");
  }
}

修改实现类

?
1
2
3
4
5
public class interfaceaimpl implements interfacea,interfaceb{
  @override
  public void showdefault() {
    system.out.println("interfaceaimpl ++ showdefault");
  }

测试结果

interfacea++showstatic
interfaceaimpl ++ showdefault

总结

看了接口中新增的这个新特性,感觉还是不错的,内容也比较简单。需要注意一点就是如果实现多个接口时,每个接口都有相同的default方法需要重写该方法。

以上所述是小编给大家介绍的java8新特性之interface中的static方法和default方法,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对服务器之家网站的支持!

原文链接:http://www.cnblogs.com/zhenghengbin/p/9398682.html