英文:
Is it right to use extend and implement in the same class?
问题
interface A {
void someMethod();
}
class B implements A {
void someMethod() {
//do something
}
}
class C extends B implements A {
void someMethod() {
super.someMethod();
//do something
}
}
我在我的代码中使用了上述的设计。它运行得很好。我在这里的整个目的是使用类B的默认实现,并在类C中执行额外操作。 这是使用实现的正确方式吗?还有其他更好的设计模式可以考虑吗?
因为如果我将我的类C定义如下,仍然一切都可以正常工作。但这忽略了使用实现的整个目的(强制类C实现接口A的方法)。
class C extends B implements A {}
英文:
interface A {
void someMethod();
}
class B implements A {
void someMethod() {
//do something
}
}
class C extends B implements A {
void someMethod() {
super.someMethod();
//do something
}
}
I'm using the above design in one of my codes. It is working fine. My whole purpose here is to use the default implementation of class B and do something extra in class C. Is this the correct way to use the implementation? Is there any better design patter to be looked at?
Because If I define my class C as below, still everything works fine. But this neglects the whole purpose of using implementation (to force class C to implement methods of interface A).
class C extends B implements A {}
答案1
得分: 0
是的,在同一类上进行扩展和实现都是完全可以的。
事实上,如果你看一下 HashMap
(以及许多其他类),那就正是它的做法:
public class HashMap<K,V> extends AbstractMap<K,V> implements Map<K,V>, Cloneable, Serializable
英文:
Yes, it's perfectly fine to both extend and implement on the same classes.
in fact, if you'll look at HashMap
(and many others), that's exactly what it does:
public class HashMap<K,V> extends AbstractMap<K,V> implements Map<K,V>, Cloneable, Serializable
答案2
得分: 0
因为当您扩展B时,它会随之附带一种someMethod的实现,从而满足契约,所以它仍然能够正常工作。
英文:
It still works fine because when you extend B that comes along with an implementation of someMethod, thus fulfilling the contract.
答案3
得分: 0
请理解,class C extends B implements A
与 class C extends B
完全相等,除了快速文档说明的目的。
尝试从 class C
中移除对 someMethod()
的定义,然后看看你的代码是否能够编译。它将能够编译通过。原因是,一旦你让 C
扩展了 B
,C
默认会获得在 B
中定义的所有方法,其中也包括了 someMethod()
的实现。这违背了你明确的约定的初衷。
如果你真的想要强制 C
提供对 someMethod()
的定义,那么尝试以下代码:
interface A {
void someMethod();
}
abstract class B implements A {
protected void someUtilMethod() {
//做一些通用/默认的定义
}
}
class C extends B {
void someMethod() {
someUtilMethod();
//做一些额外的操作
}
}
英文:
Please understand that
class C extends B implements A
is exactly equal to class C extends B
other than the quick documentation purpose.
Try removing the defination of someMethod()
from class C
and see if your code compiles or not. It will compile. The reason is, the moment you made C
extend B
, C
by default gets all the methods defined in B
which includes an impementation of someMethod()
as well. Defying the whole purpose of your explicit contract.
If you really want to force C
to give a defination of someMethod()
then try the following code:
interface A {
void someMethod();
}
abstract class B implements A {
protected void someUtilMethod() {
//do common/default defination
}
}
class C extends B {
void someMethod() {
someUtilMethod();
//do extra something
}
}
专注分享java语言的经验与见解,让所有开发者获益!
评论