实现IBaseHistory接口的类为何需重写set方法而非get方法?
接口实现类编译报错原因分析
问题场景
定义的IBaseHistory接口
public interface IBaseHistory { String getCoId(); void setPhysicalData(PhysicalData physicalData); }
实现类FunctionHistory
@Data @Accessors(chain = true) public class FunctionHistory implements Serializable, IBaseHistory { private String coId; private PhysicalData physicalData; }
编译报错信息
entity.FunctionHistory is not abstract and does not override the abstract method setPhysicalData(service.IBaseHistory.entity.PhysicalData)
删除接口中的setPhysicalData方法后程序可正常编译,疑问:为何该实现类需要重写set方法而非get方法?
原因分析
@Accessors(chain = true)改变了setter的方法签名:这个Lombok注解会让生成的setter方法返回当前类的实例(即FunctionHistory类型),而接口中定义的setPhysicalData方法返回值是void。两者方法签名不匹配,编译器判定实现类没有正确实现接口的抽象方法。- get方法签名完全匹配:
@Data注解生成的getCoId()方法返回值是String,和接口中定义的getCoId()方法的返回值、方法名、参数列表完全一致,编译器认为该方法已被正确实现,无需手动重写。 - 验证方案:如果移除
@Accessors(chain = true)注解,Lombok会生成返回值为void的setPhysicalData方法,此时方法签名与接口定义完全匹配,编译即可通过。
内容的提问来源于stack exchange,提问作者wanttobebestprogramer
相关产品推荐
相关产品推荐

