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

举报
yd_273762914 发表于 2021/07/15 22:57:20 2021/07/15
【摘要】 JDK8系列之default定义接口的默认实现方法 在前面的章节的学习中,我们学习了jdk8的新特性,lambada表达式、方法引用、函数式接口等等,接着本博客继续学习jdk8的新特性default方法 1、什么是默认方法? 默认方法,default method,这是是jdk8的新特性,只要在方法名称面前加上default关键字就行。设计出这个default方法...

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

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

1、什么是默认方法?

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

2、默认方法好处

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

interface MyInterface{ default void newMethod(){ System.out.println("this is a new method!"); }
}

  

3、默认方法例子

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

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)的

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)); }
}


  

文章来源: smilenicky.blog.csdn.net,作者:smileNicky,版权归原作者所有,如需转载,请联系作者。

原文链接:smilenicky.blog.csdn.net/article/details/118734136

【版权声明】本文为华为云社区用户转载文章,如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱: cloudbbs@huaweicloud.com
  • 点赞
  • 收藏
  • 关注作者

评论(0

0/1000
抱歉,系统识别当前为高风险访问,暂不支持该操作

全部回复

上滑加载中

设置昵称

在此一键设置昵称,即可参与社区互动!

*长度不超过10个汉字或20个英文字符,设置后3个月内不可修改。

*长度不超过10个汉字或20个英文字符,设置后3个月内不可修改。