如何解决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
...
}
解决方法
您是否希望您的具有覆盖的类能够以与原始类的成员相同的方式使用?即:
...
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 不做你的事情),而且可能不清楚哪个应该被调用。
即使是重写方法的继承也可能有问题。我们不知道 YourClass 中的哪些代码调用了 doIt
,所以我们添加的代码可能会在我们不希望它被调用时被调用。
总的来说,只要有可能,组合应该优先于继承。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。