下面這段代碼,IDE里正常顯示,不過,在build時,會報錯,
interface Doable { Integer getCode(); } @lombok.Getter class DerivedClass implements Doable { int code; }
錯誤資訊:
Error:(11, 5) java: DerivedClass不是抽象的, 并且未覆寫Doable中的抽象方法getCode()
Error:(13, 13) java: DerivedClass中的getCode()無法實作Doable中的getCode()
回傳型別int與java.lang.Integer不兼容
下面代碼,IDE直接在int上標紅線,提示錯誤:'getCode()' in 'DerivedClass' clashes with 'getCode()' in 'Doable'; attempting to use incompatible return type
interface Doable { Integer getCode(); } class DerivedClass implements Doable { @Override public int getCode() { return 1; } }
關于OOP中的方法覆寫,遵從“一大兩小”原則,其中“兩小”中的一個“小”是派生類的回傳值型別應≤父類,就是說,下面代碼是沒有問題的,
interface Doable { Number getCode(); } class DerivedClass implements Doable { @Override public Integer getCode() { return 1; } }
關于lombok的@Getter注解,首先要知道,我們熟知的lombok,分為lombok工具和lombok插件(IDEA插件:IntelliJ Lombok plugin),lombok工具在代碼編譯期為類生成相應的方法代碼,lombok插件是為類IDE增強類里的方法,就是說,lombok為類生成相關方法簽名(就像我們人肉為類添加的方法那樣,只不過插件是自動生成的),并告訴IDE,像上面的案例中,IDEA就檢測到DerivedClass類中有getCode方法,所以不會給出錯誤提示,而在編譯期,lombok工具為DerivedClass生成了int getCode方法,這時,IDEA編譯器發現因不符合java覆寫原則而報錯,
之所以分享這個知識點,則源自昨天的一段代碼, 我在專案中新增了一個列舉類PlatOrderInTypeEnum,見下面代碼,其中的EnumAbility<T>中有T getCode();方法,自然是想不到會有什么問題,結果在部署到測驗環境時,Jenkins構建時出現如下maven compile error,
/*** * T_Plat_order表IN_TYPE列舉--用來標記交易來源 (API/客戶提交/運營提交) * @author zhangguozhan * 2023-5-15 17:46:02 */ @Getter @AllArgsConstructor @EnumGetByCode public enum PlatOrderInTypeEnum implements EnumAbility<Integer> { API(1, "結算介面提交"), MERCHANT(0, "結算后臺提交"), BOSS(2, "運營后臺匯入"); private Integer code; private String description; }
Jenkins錯誤截圖

當看到一些不好的代碼時,會發現我還算優秀;當看到優秀的代碼時,也才意識到持續學習的重要!--buguge
本文來自博客園,轉載請注明原文鏈接:https://www.cnblogs.com/buguge/p/17405491.html
<style>hr.signhr{width:80%;margin:0 auto;border: 0;height: 4px;background-image: linear-gradient(to right, rgba(0, 0, 0, 0), rgba(0, 0, 0, 0.75), rgba(0, 0, 0, 0))}</style>
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/552603.html
標籤:Java
下一篇:返回列表
