interface中的static方法和default方法

目前所在的公司用的是JDK8,并且在开发和框架中用了大量的JDK8的新特性,Stream方法就是接口Collection中的default方法。这篇文章整理一下JDK8中对于Interface的改进和升级。

static方法

Java8中为Interface新增了一项功能,可以在Interface中定义一个或者更多个静态方法,用法和普通的static方法一样。代码示例:

public interface InterfaceA {
    
    
  /**
   * 静态方法
   */
  static void showStatic() {
    
    
    System.out.println("InterfaceA++showStatic");
  }
}

测试:

public class Test {
    
    
  public static void main(String[] args) {
    
    
    InterfaceA.show();
  }
}

结果:

InterfaceA++showStatic

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

default方法

JDK8中的另一个特性就是在接口中增加default方法, 是为了既有的成千上万的Java类库的类增加新的功能, 且不必对这些类重新进行设计。

比如, 只需在Collection接口中增加default Stream stream(), 相应的Set和List接口以及它们的子类都包含此的方法, 不必为每个子类都重新copy这个方法。

default这个关键字,平时见到的场景很少,使用的也不多。印象中有用到的地方,如下:

  1. switch case这个就是用在最后,所有条件都不匹配,默认进行处理。

  2. 自定义注解会有用到,给予一个默认值。

  3. 在接口中使用这个关键字。

当你很多个impl都去实现 这个接口, 而每个impl都是要包含同一个方法的时候,那么你可以直接在接口里面实现这个方法,并使用default修饰。

例如,建筑工人出行,教师出行,程序员出行, 他们都需要实现一个出行的接口,他们的出行方式不同,有骑自行车,有坐公交,有搭地铁等等, 但是他们都有一个相同的行为, ‘需要戴口罩’。 那么这个 戴口罩 的方法就可以放在接口 Interface中 使用关键字 default 修饰。

创建 Interface接口, GoOutService.class,代码如下:

public interface GoOutService {
    
    
 
    //公共行为,戴口罩
    default void wearMask(Boolean b){
    
    
        if (b){
    
    
            System.out.println("已戴,安全出行,为己为人");
        }else {
    
    
            System.out.println("sorry");
        }
 
 
    }
 
    //出行方式
    void goOutWay(Boolean b);
 
 
    //看天气
    static  void getWeatherInfo(Boolean b){
    
    
        System.out.println("今日天晴,可出行");
    }
 
    
}

接着是分别的程序员和教师的出行实现类:

ItManGoOutImpl.class:

import org.springframework.stereotype.Service;
 
@Service
public class ItManGoOutImpl implements GoOutService {
    
    
 
 
    @Override
    public void goOutWay(Boolean b) {
    
    
        System.out.println("ItMan 坐地铁");
    }
}

TeacherGoOutImpl.class:

import org.springframework.stereotype.Service;
 
@Service
public class TeacherGoOutImpl implements GoOutService  {
    
    
 
 
    @Override
    public void goOutWay(Boolean b) {
    
    
        System.out.println("Teacher 骑自行车");
    }
}

最后弄个小接口看看效果:

MyController.class:

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
public class MyController {
    
    
 
 
    @Autowired
    GoOutService itManGoOutImpl;
    @Autowired
    GoOutService   teacherGoOutImpl;
    @ResponseBody
    @GetMapping("/myTest")
    public void myTest() {
    
    
        Boolean b = true;
        itManGoOutImpl.wearMask(b);
        itManGoOutImpl.goOutWay(b);
        teacherGoOutImpl.wearMask(b);
        teacherGoOutImpl.goOutWay(b);
 
    }
 
}

运行效果:

img

从运行结果可以看到,ItManGoOutImpl以及TeacherGoOutImpl并没有wearMask方法的实现,但是依然可以直接调用GoOutService中的default方法,这就是default的特性。

完!

猜你喜欢

转载自blog.csdn.net/qusikao/article/details/127899689
今日推荐