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 {@Overridepublic 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 {@Overridepublic 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 {@AutowiredGoOutService itManGoOutImpl;@AutowiredGoOutService 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修飾 ,這兩種情況是不一樣的!
總結
以上是生活随笔為你收集整理的Java 在接口Interface中 使用关键字 default的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 从发不起工资到融资1650万,逸创创始人
- 下一篇: 【SDCC 2016现场】数据库/大数据