本文共 1399 字,大约阅读时间需要 4 分钟。
在Java编程中,default是一个关键字,通常用于接口方法的实现中。当接口定义了多个实现类(impl),并且这些实现类都需要实现同一个方法时,使用default修饰符可以在接口中直接定义一个通用的实现。这种情况下,所有实现类都会继承这个默认实现。
假设有多个具体实现类,如程序员、教师等,它们都需要实现一个公共的行为。例如,在疫情防控中,戴口罩是一个普遍的行为。我们可以将这个行为定义在接口中使用default修饰。
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("今日天晴,可出行"); }}
public class ItManGoOutImpl implements GoOutService { @Override public void goOutWay(Boolean b) { System.out.println("ItMan 坐地铁"); }}public class TeacherGoOutImpl implements GoOutService { @Override public void goOutWay(Boolean b) { System.out.println("Teacher 骑自行车"); }}
@RestControllerpublic class MyController { @Autowired private GoOutService itManGoOutImpl; @Autowired private GoOutService teacherGoOutImpl; @GetMapping("/myTest") public void myTest() { Boolean b = true; itManGoOutImpl.wearMask(b); itManGoOutImpl.goOutWay(b); teacherGoOutImpl.wearMask(b); teacherGoOutImpl.goOutWay(b); }}
@Service
注解注册实现类。这种方法简化了接口实现的复杂性,使得所有实现类共享相同的行为。
转载地址:http://fjwb.baihongyu.com/