java - java Super.call有什么最佳实践吗?
问题描述
public boolean sendRequest(final Object... params) {
if (!super.sendRequest(params)) {
return false;
}
...
// Some Log code or tracing code here
...
}
为什么不实现一个新方法来调用 sendRequest 而不是覆盖?
public boolean Send(final Object... params){
if (!super.sendRequest(params)) {
return false;
}
...
// Some Log code or tracing code here
...
}
解决方案
您是否希望具有覆盖的类能够以与原始类成员相同的方式使用?IE:
...
class MyClass extends TheirClass {
@Override
void doIt() {
super.doIt();
// also do my stuff
}
}
...
// the doSomething function is part of the library where TheirClass lives.
// I can pass instances of MyClass to it, and doIt will be called, because MyClass IS-A TheirClass
theirFunction.doSomething(new MyClass(...));
...
但也许您只是想使用 的功能doIt
,而不需要使用期望TheirClass
.
在这种情况下,最好使用组合而不是继承:
class MyClass {
private final TheirClass theirClass;
public MyClass(TheirClass theirClass) {
this.theirClass = theirClass;
}
public void doMyStuff() {
theirClass.doIt();
// and do some other things
}
}
这比使用新方法名的继承要好,因为这样你就会在类上有两个方法做同样的事情(除了原来的 doIt 不做你的事情),并且可能不清楚应该调用哪个.
即使是覆盖方法的继承也可能有问题。我们不知道 TheyClass 中调用了什么代码doIt
,所以我们添加的代码可能会在我们不期望的时候被调用。
总的来说,只要有可能,组合应该优先于继承。
推荐阅读
- python - 即使在成功连接并在 kafka 消费者控制台中获取消息后,也无法使用来自 kafka 主题的消息(使用 Python)
- verilog - 关于 Verilog 中的 $monitor,粗体线是什么意思?
- javascript - 如何要求用户打开他们的蓝牙?使用 javascript
- node.js - 没有错误地触发子进程功能
- spring-boot - Gradle5.2 中的 Gradle kotlin 未解决的参考:dependtest
- c# - 值不能为空。参数名称:连接字符串
- python - LookupError:没有安装标签为“管理员”的应用程序。当我尝试使用 Django 运行程序时
- artifactory - 如何在 Artifactory REST API 中使用可选标头?
- c# - 类内对象的列表或字典
- react-native - 嵌套导航器