Java 8中的默认方法(Defender方法)简介

我们都知道Java中的接口仅包含方法声明,而没有实现,并且任何实现该接口的非抽象类都必须提供实现。 让我们看一个例子:

public interface SimpleInterface {
  public void doSomeWork();
}

class SimpleInterfaceImpl implements SimpleInterface{
  @Override
  public void doSomeWork() {
    System.out.println('Do Some Work implementation in the class');
  }

  public static void main(String[] args) {
    SimpleInterfaceImpl simpObj = new SimpleInterfaceImpl();
    simpObj.doSomeWork();
  }
}

现在,如果我在SimpleInterface中添加新方法怎么办?

public interface SimpleInterface {
  public void doSomeWork();
  public void doSomeOtherWork();
}

如果我们尝试编译代码,最终结果是:

$javac .\SimpleInterface.java
.\SimpleInterface.java:18: error: SimpleInterfaceImpl is not abstract and does not 
override abstract method doSomeOtherWork() in SimpleInterface
class SimpleInterfaceImpl implements SimpleInterface{
^
1 error

这种限制使得几乎不可能扩展/改进现有的接口和API。 在Java 8中增强Collections API以在API中支持lambda表达式时,面临着同样的挑战。 为了克服此限制,Java 8中引入了一个称为默认方法的新概念,该默认方法也称为Defender方法或虚拟扩展方法。

默认方法是具有一些默认实现的那些方法,它们有助于在不破坏现有代码的情况下扩展接口。 让我们看一个例子:

public interface SimpleInterface {
  public void doSomeWork();

  //A default method in the interface created using 'default' keyword
  default public void doSomeOtherWork(){
    System.out.println('DoSomeOtherWork implementation in the interface');
  }
}

class SimpleInterfaceImpl implements SimpleInterface{
  @Override
  public void doSomeWork() {
    System.out.println('Do Some Work implementation in the class');
  }
  /*
   * Not required to override to provide an implementation 
   * for doSomeOtherWork.
   */

  public static void main(String[] args) {
    SimpleInterfaceImpl simpObj = new SimpleInterfaceImpl();
    simpObj.doSomeWork();
    simpObj.doSomeOtherWork();
  }
}

输出为:

Do Some Work implementation in the class
DoSomeOtherWork implementation in the interface

这是对默认方法的非常简短的介绍。 在这里可以深入了解默认方法。

参考:来自JCG合作伙伴 Mohamed Sanaulla的Java 8中的默认方法(防御方法)简介,网址为Experiences Unlimited

翻译自: https://www.javacodegeeks.com/2013/03/introduction-to-default-methods-defender-methods-in-java-8.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值