1. 继承层次过深问题
继承层次过深会导致代码难以理解和维护,还可能引发性能问题。
问题案例
class animal { protected string name; public void setname(string name) { this.name = name; } public string getname() { return name; } public void eat() { system.out.println(name + " is eating"); } } class mammal extends animal { protected int legcount; public void setlegcount(int legcount) { this.legcount = legcount; } public int getlegcount() { return legcount; } public void walk() { system.out.println(name + " is walking with " + legcount + " legs"); } } class canine extends mammal { protected boolean hastail; public void sethastail(boolean hastail) { this.hastail = hastail; } public boolean hastail() { return hastail; } public void bark() { system.out.println(name + " is barking"); } } class dog extends canine { private string breed; public void setbreed(string breed) { this.breed = breed; } public string getbreed() { return breed; } public void fetch() { system.out.println(name + " is fetching"); } } class germanshepherd extends dog { // 继承链已经很长了 public void guard() { system.out.println(name + " is guarding"); } }
这个继承链中包含了 5 个层级,当我们使用germanshepherd
类时:
germanshepherd dog = new germanshepherd(); dog.setname("max"); // 通过setter设置名称 dog.setlegcount(4); // 设置腿的数量 dog.sethastail(true); // 设置是否有尾巴 dog.guard(); // 当前类方法
问题分析
- 代码可读性差:必须追溯多个父类才能理解完整功能
- 方法解析层级深:jvm 需从子类到父类逐层查找方法,增加动态绑定开销
- 修改基类影响大:修改 animal 类可能影响整个继承链
从字节码层面看,深层继承导致方法调用时 jvm 需要执行更多invokevirtual
指令来查找方法实现:
# 继承链方法调用 javap -c germanshepherd | grep invokevirtual # 输出类似: # 15: invokevirtual #8 // method getname:()ljava/lang/string; # 25: invokevirtual #10 // method bark:()v
优化方案
组合优先于继承:将部分功能抽取为接口和独立类,通过组合方式使用
// 定义行为接口 interface locomotionbehavior { void move(string name); } interface guardbehavior { void guard(string name); } // 行为集合类 class behaviorset { private final locomotionbehavior locomotion; private final guardbehavior guardbehavior; public behaviorset(locomotionbehavior locomotion, guardbehavior guardbehavior) { this.locomotion = locomotion; this.guardbehavior = guardbehavior; } public locomotionbehavior getlocomotion() { return locomotion; } public guardbehavior getguardbehavior() { return guardbehavior; } } class animal { private string name; public animal(string name) { this.name = name; } public string getname() { return name; } public void eat() { system.out.println(name + " is eating"); } } class quadrupedlocomotion implements locomotionbehavior { private int legcount; public quadrupedlocomotion(int legcount) { this.legcount = legcount; } @override public void move(string name) { system.out.println(name + " is moving with " + legcount + " legs"); } } class activeguardbehavior implements guardbehavior { @override public void guard(string name) { system.out.println(name + " is actively guarding the area"); } } class dog extends animal { private final behaviorset behaviors; private boolean hastail; private string breed; public dog(string name, int legcount, boolean hastail, string breed) { super(name); locomotionbehavior locomotion = new quadrupedlocomotion(legcount); guardbehavior guardbehavior = new activeguardbehavior(); this.behaviors = new behaviorset(locomotion, guardbehavior); this.hastail = hastail; this.breed = breed; } public void move() { behaviors.getlocomotion().move(getname()); } public void performguard() { behaviors.getguardbehavior().guard(getname()); } public void bark() { system.out.println(getname() + " is barking"); } }
字节码层面的比较:
# 组合方案方法调用 javap -c dog | grep invokeinterface # 输出类似: # 10: invokeinterface #6, 2 // interfacemethod locomotionbehavior.move:(ljava/lang/string;)v
使用组合后,我们可以通过接口实现行为的灵活组合,符合"接口隔离原则",降低了类之间的耦合度。
2. 父类变更对子类的影响
父类的修改可能会导致子类行为发生意外变化,这是 java 继承中最容易忽视的问题,即"脆弱基类问题"(fragile base class problem)。
问题案例
// 初始版本 class parent { public void process() { step1(); step2(); } protected void step1() { system.out.println("parent step1"); } protected void step2() { system.out.println("parent step2"); } } class child extends parent { @override protected void step2() { system.out.println("child step2"); } }
客户端代码:
child child = new child(); child.process(); // 输出:parent step1, child step2
后来,父类做了"看似无害"的修改:
class parent { public void process() { step1(); step2(); step3(); // 新增了一个步骤 } protected void step1() { system.out.println("parent step1"); } protected void step2() { system.out.println("parent step2"); } protected void step3() { system.out.println("parent step3"); } }
这时子类没有任何修改,但执行结果变成了:parent step1, child step2, parent step3
问题分析
这种问题本质上违反了"里氏替换原则"(liskov substitution principle):子类必须能替换其父类且不改变程序正确性。子类对父类实现细节的依赖是设计问题的根源。
优化方案
模板方法模式:父类定义整体流程,子类实现特定步骤
class parent { // final防止子类覆盖整个流程 public final void process() { step1(); step2(); step3(); // 钩子方法(hook method),子类可以覆盖 postprocess(); } // 可以由子类覆盖的步骤 protected void step1() { system.out.println("parent step1"); } protected void step2() { system.out.println("parent step2"); } protected void step3() { system.out.println("parent step3"); } // 钩子方法,默认为空实现 protected void postprocess() { // 默认空实现 } }
策略模式:比模板方法更灵活,适合步骤可动态替换的场景
interface processstrategy { void execute(list<?> data); // 明确处理的数据 } class defaultprocessstrategy implements processstrategy { @override public void execute(list<?> data) { system.out.println("processing " + data.size() + " items"); } } class parent { private processstrategy processstrategy; private list<?> data; public parent(list<?> data) { this.data = data; this.processstrategy = new defaultprocessstrategy(); } public void setprocessstrategy(processstrategy strategy) { this.processstrategy = strategy; } public void process() { // 前置处理 preprocess(); // 委托给策略执行 processstrategy.execute(data); // 后置处理 postprocess(); } protected void preprocess() { system.out.println("pre-processing"); } protected void postprocess() { system.out.println("post-processing"); } }
spring 框架使用类似机制解决这类问题:
// 类似spring的initializingbean接口 public interface initializingbean { void afterpropertiesset() throws exception; } public abstract class abstractbean implements initializingbean { @override public void afterpropertiesset() throws exception { // 子类覆盖此方法进行初始化,而不是构造函数 initbean(); } protected abstract void initbean() throws exception; }
3. 构造函数与初始化顺序问题
继承中构造函数的调用顺序和初始化逻辑常常是错误的根源。
问题案例
class parent { private int value; public parent() { init(); // 在构造函数中调用可能被子类覆盖的方法 } protected void init() { value = 10; } public int getvalue() { return value; } } class child extends parent { // 显式初始化,未在构造函数中赋值 private int childvalue = 20; @override protected void init() { super.init(); // 父类构造调用此方法时,childvalue已初始化为20 // 但子类构造函数尚未执行完毕 childvalue = childvalue * 2; // 此时childvalue=20,结果为40 } public int getchildvalue() { return childvalue; } }
让我们修改示例,使问题更明显:
class child extends parent { // 不使用显式初始化 private int childvalue; public child() { childvalue = 20; // 构造函数中赋值 } @override protected void init() { super.init(); childvalue = childvalue * 2; // 此时childvalue=0(默认值),结果为0 } }
测试代码:
child child = new child(); system.out.println(child.getvalue() + ", " + child.getchildvalue()); // 期望输出:10, 40 // 实际输出:10, 0
问题分析
java 对象初始化顺序如下:
- 父类静态变量和静态块
- 子类静态变量和静态块
- 父类实例变量和实例初始化块
- 父类构造函数
- 子类实例变量和实例初始化块
- 子类构造函数
关键问题是:父类构造函数中调用的被子类覆盖的方法会在子类实例变量初始化前执行。
优化方案
不在构造函数中调用可覆盖的方法:
class parent { private int value; public parent() { // 直接初始化,不调用可能被覆盖的方法 value = 10; } // 提供初始化方法,但不在构造函数中调用 protected void init() { // 可以被子类安全覆盖 } public int getvalue() { return value; } } class child extends parent { private int childvalue; public child() { // 子类构造函数中完成自己的初始化 childvalue = 20; init(); // 安全调用,此时所有字段都已初始化 } @override protected void init() { super.init(); childvalue = childvalue * 2; // 现在childvalue是20 } public int getchildvalue() { return childvalue; } }
使用工厂方法和后置初始化:
class parent { private int value; protected parent() { value = 10; // 不调用可能被覆盖的方法 } public static parent create() { parent p = new parent(); p.postconstruct(); // 工厂方法中调用后置初始化 return p; } protected void postconstruct() { // 初始化代码放这里,子类可以安全覆盖 } public int getvalue() { return value; } } class child extends parent { private int childvalue; protected child() { // 构造函数只做最基本的初始化 childvalue = 20; } public static child create() { child c = new child(); c.postconstruct(); // 构造完成后调用 return c; } @override protected void postconstruct() { super.postconstruct(); childvalue = childvalue * 2; // 安全地修改childvalue } public int getchildvalue() { return childvalue; } }
4. equals 和 hashcode 继承问题
equals 和 hashcode 方法的正确实现对 java 集合类的正常工作至关重要,但在继承中很容易出错。
问题案例
class point { private final int x; private final int y; public point(int x, int y) { this.x = x; this.y = y; } public int getx() { return x; } public int gety() { return y; } @override public boolean equals(object obj) { if (this == obj) return true; if (obj == null || getclass() != obj.getclass()) return false; point point = (point) obj; return x == point.x && y == point.y; } @override public int hashcode() { return 31 * x + y; } } class colorpoint extends point { private string color; // 不是final,可变 public colorpoint(int x, int y, string color) { super(x, y); this.color = color; } public string getcolor() { return color; } public void setcolor(string color) { this.color = color; } @override public boolean equals(object obj) { if (!super.equals(obj)) return false; // 这里有问题:父类的equals已经做了getclass检查,这里类型转换可能出错 colorpoint colorpoint = (colorpoint) obj; return objects.equals(color, colorpoint.color); } // 没有覆盖hashcode! }
测试代码:
point p = new point(1, 2); colorpoint cp1 = new colorpoint(1, 2, "red"); colorpoint cp2 = new colorpoint(1, 2, "blue"); system.out.println(p.equals(cp1)); // false - 类型不匹配 system.out.println(cp1.equals(p)); // classcastexception! - 无法将point转为colorpoint map<colorpoint, string> map = new hashmap<>(); map.put(cp1, "first point"); system.out.println(map.get(cp1)); // "first point" cp1.setcolor("green"); // 修改了影响hashcode的字段 system.out.println(map.get(cp1)); // null - 找不到了!
问题分析
- equals 违反了对称性:p.equals(cp1)与 cp1.equals(p)结果不一致,甚至抛出异常
- 没有覆盖 hashcode,违反了"equals 相等则 hashcode 必须相等"的约定
- 可变对象作为 hashmap 的键会导致数据丢失
《effective java》明确指出 equals 必须满足:
- 自反性:x.equals(x)为 true
- 对称性:x.equals(y)为 true 当且仅当 y.equals(x)为 true
- 传递性:x.equals(y)为 true 且 y.equals(z)为 true,则 x.equals(z)为 true
- 一致性:多次调用 x.equals(y)结果一致
优化方案
组合优先于继承:
class point { private final int x; private final int y; public point(int x, int y) { this.x = x; this.y = y; } public int getx() { return x; } public int gety() { return y; } @override public boolean equals(object obj) { if (this == obj) return true; if (obj == null || getclass() != obj.getclass()) return false; point point = (point) obj; return x == point.x && y == point.y; } @override public int hashcode() { return 31 * x + y; } @override public string tostring() { return "point[x=" + x + ", y=" + y + "]"; } } // 使用组合而非继承 class colorpoint { private final point point; private final string color; public colorpoint(int x, int y, string color) { this.point = new point(x, y); this.color = color; } // 委托方法 public int getx() { return point.getx(); } public int gety() { return point.gety(); } public string getcolor() { return color; } // 防御性拷贝,避免外部修改 public point aspoint() { return new point(point.getx(), point.gety()); } @override public boolean equals(object obj) { if (this == obj) return true; if (obj == null || getclass() != obj.getclass()) return false; colorpoint that = (colorpoint) obj; return point.equals(that.point) && objects.equals(color, that.color); } @override public int hashcode() { return 31 * point.hashcode() + objects.hashcode(color); } @override public string tostring() { return "colorpoint[point=" + point + ", color=" + color + "]"; } }
使用 java 16+记录类(record):
// 使用记录类自动实现equals、hashcode、tostring record point(int x, int y) {} record colorpoint(point point, string color) { // 自定义构造函数验证参数 public colorpoint { if (color == null) { throw new nullpointerexception("color cannot be null"); } } // 便捷方法 public int x() { return point.x(); } public int y() { return point.y(); } } // 使用示例 point p = new point(1, 2); colorpoint cp = new colorpoint(p, "red"); system.out.println(cp.point().x()); // 1
5. 父类方法重写问题
方法重写是 java 多态的基础,但不恰当的重写会带来意外问题。
问题案例
class dataprocessor { protected list<integer> data; public dataprocessor(list<integer> data) { this.data = data; } public void process() { for (int i = 0; i < data.size(); i++) { processitem(i); } } protected void processitem(int index) { data.set(index, data.get(index) * 2); } } class filterprocessor extends dataprocessor { private int threshold; public filterprocessor(list<integer> data, int threshold) { super(data); this.threshold = threshold; } @override protected void processitem(int index) { if (data.get(index) > threshold) { super.processitem(index); } } }
现在基类开发者修改了代码:
class dataprocessor { // 其他代码不变 public void process() { // 修改了遍历顺序 for (int i = data.size() - 1; i >= 0; i--) { processitem(i); } } }
问题分析
子类依赖了父类的实现细节(遍历顺序),当父类修改实现时,子类行为可能发生变化。这违反了"里氏替换原则",子类不能完全替代父类使用。
里氏替换原则的典型反例:
// 矩形/正方形问题 class rectangle { private int width; private int height; public void setwidth(int width) { this.width = width; } public void setheight(int height) { this.height = height; } public int getarea() { return width * height; } } class square extends rectangle { @override public void setwidth(int width) { super.setwidth(width); super.setheight(width); // 正方形要求宽高相等 } @override public void setheight(int height) { super.setheight(height); super.setwidth(height); // 正方形要求宽高相等 } } // 使用代码 rectangle rect = new square(); rect.setwidth(5); rect.setheight(10); int area = rect.getarea(); // 期望50,实际100
优化方案
使用组合和回调:
// 回调接口 interface itemprocessor { void process(list<integer> data, int index); } class dataprocessor { protected list<integer> data; private itemprocessor itemprocessor; public dataprocessor(list<integer> data, itemprocessor itemprocessor) { this.data = data; this.itemprocessor = itemprocessor; } public void process() { // 实现可以变化,但接口稳定 for (int i = 0; i < data.size(); i++) { itemprocessor.process(data, i); } } // 默认处理器作为静态工厂方法 public static dataprocessor createdefault(list<integer> data) { return new dataprocessor(data, (list, index) -> list.set(index, list.get(index) * 2)); } } // 过滤处理器 class filterprocessor implements itemprocessor { private int threshold; private itemprocessor wrapped; public filterprocessor(int threshold, itemprocessor wrapped) { this.threshold = threshold; this.wrapped = wrapped; } @override public void process(list<integer> data, int index) { if (data.get(index) > threshold) { wrapped.process(data, index); } } }
使用示例:
list<integer> data = new arraylist<>(arrays.aslist(1, 5, 10, 15, 20)); // 创建处理器 itemprocessor doubler = (list, index) -> list.set(index, list.get(index) * 2); itemprocessor filtered = new filterprocessor(7, doubler); dataprocessor processor = new dataprocessor(data, filtered); // 处理数据 processor.process();
6. 抽象类与接口的选择问题
错误的抽象方式会导致继承体系僵化,限制扩展性。
问题案例
// 错误设计:将具体实现放在抽象类中 abstract class abstractrepository { private connection connection; public abstractrepository() { // 固定的数据库连接初始化 try { connection = drivermanager.getconnection("jdbc:mysql://localhost/db", "user", "pass"); } catch (sqlexception e) { throw new runtimeexception(e); } } // 通用的crud操作 public void save(object entity) { // 保存实现... } public object findbyid(long id) { // 查询实现... return null; } // 子类需要实现的抽象方法 protected abstract string gettablename(); } // 用户仓库 class userrepository extends abstractrepository { @override protected string gettablename() { return "users"; } // 特有方法 public user findbyusername(string username) { // 实现... return null; } } // 订单仓库 class orderrepository extends abstractrepository { @override protected string gettablename() { return "orders"; } // 需要使用不同的数据库连接,但无法修改 }
问题分析
- 抽象类中包含了具体实现,所有子类都被迫继承这些实现
- 子类无法选择不同的数据库连接策略
- 如果需要实现新的存储方式(如 nosql),整个继承体系都要重写
优化方案
接口+默认实现类:
// 接口定义行为 interface repository<t, id> { void save(t entity); t findbyid(id id); list<t> findall(); } // 连接工厂接口 interface connectionfactory { connection getconnection() throws sqlexception; } // 默认mysql连接工厂 class mysqlconnectionfactory implements connectionfactory { @override public connection getconnection() throws sqlexception { return drivermanager.getconnection("jdbc:mysql://localhost/db", "user", "pass"); } } // 行映射接口 interface rowmapper<t> { t maprow(resultset rs) throws sqlexception; } // 默认实现类 class jdbcrepository<t, id> implements repository<t, id> { private final connectionfactory connectionfactory; private final string tablename; private final rowmapper<t> rowmapper; // 构造函数注入,符合依赖倒置原则 public jdbcrepository(connectionfactory connectionfactory, string tablename, rowmapper<t> rowmapper) { this.connectionfactory = connectionfactory; this.tablename = tablename; this.rowmapper = rowmapper; } @override public void save(t entity) { // 实现... } @override public t findbyid(id id) { // 实现... return null; } @override public list<t> findall() { // 实现... return null; } } // 使用组合方式创建特定仓库 class userrepository { private final repository<user, long> repository; public userrepository(connectionfactory connectionfactory) { this.repository = new jdbcrepository<>( connectionfactory, "users", rs -> { // 映射用户对象 user user = new user(); user.setid(rs.getlong("id")); user.setusername(rs.getstring("username")); return user; } ); } // 委托方法 public void save(user user) { repository.save(user); } public user findbyid(long id) { return repository.findbyid(id); } // 特有方法 public user findbyusername(string username) { // 实现... return null; } }
7. 序列化与继承问题
在涉及序列化的继承关系中,常常会出现意外的问题。
问题案例
class parent implements serializable { private static final long serialversionuid = 1l; private int parentvalue; public parent() { initparent(); } protected void initparent() { parentvalue = 10; } public int getparentvalue() { return parentvalue; } } class child extends parent implements serializable { private static final long serialversionuid = 1l; private int childvalue; public child() { initchild(); } protected void initchild() { childvalue = 20; } @override protected void initparent() { super.initparent(); childvalue = 30; // 父类构造调用时,childvalue尚未初始化 } public int getchildvalue() { return childvalue; } }
测试代码:
// 序列化 bytearrayoutputstream bos = new bytearrayoutputstream(); objectoutputstream oos = new objectoutputstream(bos); child child = new child(); oos.writeobject(child); // 反序列化 bytearrayinputstream bis = new bytearrayinputstream(bos.tobytearray()); objectinputstream ois = new objectinputstream(bis); child deserializedchild = (child) ois.readobject(); // 反序列化后的对象状态可能不一致
问题分析
反序列化过程不会调用构造函数,而是直接恢复字段值,这可能导致对象处于不一致状态,特别是当子类覆盖了父类方法且方法之间有依赖关系时。
优化方案
添加 readobject 钩子:
class parent implements serializable { private static final long serialversionuid = 1l; private int parentvalue; public parent() { initvalues(); } // 初始化逻辑单独提取 protected void initvalues() { parentvalue = 10; } // 反序列化钩子 private void readobject(objectinputstream ois) throws ioexception, classnotfoundexception { ois.defaultreadobject(); // 恢复不可序列化的状态 postdeserialize(); } // 反序列化后的处理 protected void postdeserialize() { // 默认不做任何事 } public int getparentvalue() { return parentvalue; } } class child extends parent { private static final long serialversionuid = 1l; private int childvalue; public child() { // 父类构造已经调用过initvalues } @override protected void initvalues() { super.initvalues(); childvalue = 20; } @override protected void postdeserialize() { super.postdeserialize(); // 反序列化后的特殊处理 validatestate(); } private void validatestate() { if (childvalue <= 0) { childvalue = 20; // 恢复默认值 } } // 自定义反序列化钩子 private void readobject(objectinputstream ois) throws ioexception, classnotfoundexception { ois.defaultreadobject(); // 不需要显式调用postdeserialize,父类的readobject会调用 } public int getchildvalue() { return childvalue; } }
使用工厂方法和 builder 模式:
class parentbuilder { private int parentvalue = 10; // 默认值 public parentbuilder withparentvalue(int value) { this.parentvalue = value; return this; } public parent build() { parent parent = new parent(); parent.setparentvalue(parentvalue); return parent; } } class parent implements serializable { private static final long serialversionuid = 1l; private int parentvalue; // 包级私有构造函数,强制使用builder parent() {} void setparentvalue(int value) { this.parentvalue = value; } public static parentbuilder builder() { return new parentbuilder(); } public int getparentvalue() { return parentvalue; } }
8. 协变返回类型与泛型问题
java 支持协变返回类型,但在继承和泛型结合时容易出现问题。
问题案例
class animal { public animal reproduce() { return new animal(); } } class dog extends animal { @override public dog reproduce() { // 协变返回类型 return new dog(); } } // 泛型容器 class container<t> { private t value; public void setvalue(t value) { this.value = value; } public t getvalue() { return value; } } class animalcontainer extends container<animal> { // 尝试覆盖泛型方法 @override public animal getvalue() { return super.getvalue(); } } class dogcontainer extends animalcontainer { // 不能使用协变返回类型 // @override // public dog getvalue() { // 编译错误 // return (dog) super.getvalue(); // } }
问题分析
泛型类型擦除导致在继承层次中无法正确应用协变返回类型。虽然dog
是animal
的子类,但container<dog>
不是container<animal>
的子类。
优化方案
泛型通配符和自限定类型:
abstract class animal<t extends animal<t>> { @suppresswarnings("unchecked") public t reproduce() { try { return (t) getclass().getdeclaredconstructor().newinstance(); } catch (exception e) { throw new runtimeexception(e); } } } class dog extends animal<dog> { // 无需覆盖reproduce方法,自动返回正确类型 } // 容器设计 interface container<t, s extends container<t, s>> { t getvalue(); s setvalue(t value); } class genericcontainer<t> implements container<t, genericcontainer<t>> { private t value; @override public t getvalue() { return value; } @override public genericcontainer<t> setvalue(t value) { this.value = value; return this; } } class dogcontainer extends genericcontainer<dog> { // 自动继承正确的返回类型 }
总结
下面是 java 继承复用中常见问题及解决方案的总结:
问题类型 | 代码审查关键点 | 推荐解决方案 | 重构工具建议 |
---|---|---|---|
继承层次过深 | 类层级>3 层,使用protected 字段超过 3 个 | 使用组合+接口替代继承,控制继承层次不超过 2 层 | idea 的"extract interface"和"replace inheritance with delegation" |
父类变更影响 | 子类依赖父类实现细节,父类方法被子类广泛覆盖 | 使用模板方法模式,或用组合+策略模式替代继承 | idea 的"extract method"和"extract delegate" |
构造函数问题 | 构造函数中调用可覆盖方法,子类构造中使用super 以外的代码 | 避免在构造函数中调用可覆盖方法,使用工厂方法+后置初始化 | findbugs 的"se_method_must_be_private" |
equals/hashcode 错误 | 未正确覆盖 hashcode,使用 instanceof 或==比较对象引用 | 优先使用组合而非继承,确保 equals/hashcode 符合约定 | findbugs 的"eq_doesnt_override_hashcode" |
方法重写问题 | 子类依赖父类实现细节,违反里氏替换原则 | 使用组合和回调机制,避免不当重写 | sonarqube 的"s1161"(覆盖方法应调用 super) |
抽象类滥用 | 抽象类中包含具体实现,继承链僵化 | 优先使用接口+默认实现类,通过组合实现代码复用 | idea 的"replace constructor with factory method" |
序列化问题 | 继承类序列化未处理自定义反序列化逻辑 | 添加 readobject 钩子,使用 builder 模式 | findbugs 的"se_no_suitable_constructor" |
协变返回与泛型 | 尝试在泛型类中使用协变返回类型 | 使用自限定泛型和接口隔离 | idea 的"generify" |
性能测试显示,在大型项目中,优化继承结构可以带来 5-15%的性能提升,更重要的是可维护性的大幅提高。
@state(scope.benchmark) public class inheritancevscompositionbenchmark { private germanshepherd inheritancedog; private dog compositiondog; @setup public void setup() { inheritancedog = new germanshepherd(); inheritancedog.setname("rex"); compositiondog = new dog("rex", 4, true, "german shepherd"); } @benchmark public void inheritancemethodcall(blackhole bh) { bh.consume(inheritancedog.getname()); inheritancedog.eat(); } @benchmark public void compositionmethodcall(blackhole bh) { bh.consume(compositiondog.getname()); compositiondog.eat(); } }
合理使用继承和组合是 java 面向对象编程的关键技能。记住"组合优先于继承"的原则,在适当的场景选择正确的代码复用方式,可以大大提高代码的可维护性和健壮性。
以上就是java继承复用中的常见问题与优化技巧的详细内容,更多关于java继承复用的问题与优化的资料请关注代码网其它相关文章!
发表评论