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修饰 ,这两种情况是不一样的!

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

小目标青年

对你有帮助的话,谢谢你的打赏。

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值