Java 在接口Interface中 使用关键字 default

default 这个关键字,说实话平时见到的场景很少,使用的也不多。

印象中有用到的时候,

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

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

3. 就是咱们这篇里介绍的,在接口中使用这个关键字 。

那么,开始进入主题前,我举个例子,来形容下在接口中使用这个default的场景:

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

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

实例:

创建 Interface接口,  GoOutService.class:

/**
 * @Author : JCccc
 * @CreateTime : 2020/3/10
 * @Description :
 **/
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;

/**
 * @Author : JCccc
 * @CreateTime : 2020/3/10
 * @Description :
 **/
@Service
public class ItManGoOutImpl implements GoOutService {


    @Override
    public void goOutWay(Boolean b) {
        System.out.println("ItMan 坐地铁");
    }
}

TeacherGoOutImpl.class:

import org.springframework.stereotype.Service;

/**
 * @Author : JCccc
 * @CreateTime : 2020/3/10
 * @Description :
 **/
@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;
/**
 * @Author : JCccc
 * @CreateTime : 2020/3/10
 * @Description :
 **/
@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);

    }

}

运行效果:

当然,上文中,我在接口 GoOutService里也加入了一个静态的实现方法,getWeatherInfo 看天气。

也是可以通过接口直接调用:

ok,这次的 在接口Interface中 使用关键字 default 就到此吧。

ps:
1. 如果没有在springboot或者spring框架里面使用, 可以采取通过new 实现接口实现类来进行验证使用,如,

2. 这里使用的default关键字 跟 在实体类中 定义方法不使用任何修饰符,系统默认采取default修饰 ,这两种情况是不一样的!

发布了181 篇原创文章 · 获赞 289 · 访问量 27万+

猜你喜欢

转载自blog.csdn.net/qq_35387940/article/details/104767746