前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >JDK8系列之default定义接口的默认实现方法

JDK8系列之default定义接口的默认实现方法

作者头像
SmileNicky
发布2021-07-19 15:41:43
1.1K0
发布2021-07-19 15:41:43
举报
文章被收录于专栏:Nicky's blog

JDK8系列之default定义接口的默认实现方法

前面的章节的学习中,我们学习了jdk8的新特性,lambada表达式、方法引用、函数式接口等等,接着本博客继续学习jdk8的新特性default方法

1、什么是默认方法?

默认方法,default method,这是是jdk8的新特性,只要在方法名称面前加上default关键字就行。设计出这个default方法的目的是为了添加到接口中,正常情况,接口中只能有接口,不能有实现方法的,有了default方法之后,就可以在接口中写实现。

2、默认方法好处

例如,多个类(A、B、C等等)都实现了K接口,如果我们要在K接口新加一个method方法,然后要其它实现类A,B,C都实现这个方法,这样就需要改动很多,每个实现类都要修改,所以default方法就是为了避免这种情况,可能你会说设计成抽象类就行,不用接口就行,虽然可以如此,不过就不符合“面向接口“的思想

代码语言:javascript
复制
interface MyInterface{  
    default void newMethod(){ 
    	System.out.println("this is a new method!");
    }
}

3、默认方法例子

newMethod是一个默认方法,所以实现类DefaultMethodExample就不需要实现了,直接实现抽象的otherMethod方法既可

代码语言:javascript
复制
interface TestInterface {
    default void newMethod(){
        System.out.println("This is a new method!");
    }
    void otherMethod(String str);
}
public class DefaultMethodExample implements TestInterface {
    public static void main(String[] args) {
        DefaultMethodExample example = new DefaultMethodExample();
        example.newMethod();
        example.otherMethod("hello world");
    }
    @Override
    public void otherMethod(String str) {
        System.out.println(String.format("echo:%s" , str));
    }
}

4、接口中的静态函数

使用静态函数的方法也可以替代default method,但是静态函数是不可以被重写(@Override)的

代码语言:javascript
复制
interface TestInterface {
    default void newMethod(){
        System.out.println("This is a new method!");
    }
    static void anotherNewMethod(){
        System.out.println("This is a static method");
    }
    void otherMethod(String str);
}

public class DefaultMethodExample implements TestInterface {

    public static void main(String[] args) {
        DefaultMethodExample example = new DefaultMethodExample();
        example.newMethod();
        TestInterface.anotherNewMethod();
        example.otherMethod("hello world");
    }

    @Override
    public void otherMethod(String str) {
        System.out.println(String.format("echo:%s" , str));
    }
}
本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2021/07/15 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • JDK8系列之default定义接口的默认实现方法
    • 1、什么是默认方法?
      • 2、默认方法好处
        • 3、默认方法例子
          • 4、接口中的静态函数
          领券
          问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档