java Super.call 有什么最佳实践吗?
Is there any best practice on 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 与原始 class 成员的使用方式相同?即:
...
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
}
}
这比使用新方法名继承要好,因为那样的话你会在 class 上有两个方法做同样的事情(除了原来的 doIt 不做你的事情),并且可能不清楚应该调用哪个。
即使是覆盖方法的继承也可能有问题。我们不知道 TheirClass 中的什么代码调用 doIt
,所以也许我们添加的代码会在我们不期望的时候被调用。
总的来说,只要有可能,组合应该优先于继承。
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 与原始 class 成员的使用方式相同?即:
...
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
}
}
这比使用新方法名继承要好,因为那样的话你会在 class 上有两个方法做同样的事情(除了原来的 doIt 不做你的事情),并且可能不清楚应该调用哪个。
即使是覆盖方法的继承也可能有问题。我们不知道 TheirClass 中的什么代码调用 doIt
,所以也许我们添加的代码会在我们不期望的时候被调用。
总的来说,只要有可能,组合应该优先于继承。