简体   繁体   English

语法问题-扩展实现接口的抽象类

[英]Syntax question - extending abstract classes that implement an interface

Just a simple syntax question. 只是一个简单的语法问题。 Suppose we have an interface which we will call IMyClass , and an abstract class that implements which we will call AbstractMyClass and is declared as follows: 假设我们有一个称为IMyClass的接口和一个实现我们称为AbstractMyClass的抽象类,并声明如下:

public abstract class AbstractMyClass implements IMyClass {
}

Now when we create a concrete implementation of MyClass which we will call... MyClass !, there are two ways in which we can declare it: 现在,当我们创建MyClass的具体实现时,我们将其称为... MyClass !,可以通过两种方法对其进行声明:

public class MyClass extends AbstractMyClass {
}

and

public class MyClass extends AbstractMyClass implements IMyClass {
}

What's best here? 什么是最好的? I'm supposing the answer to this is just a matter of preference but just wanted to hear some thoughts on this. 我想对此的答案只是一个偏好问题,但只是想听听对此的一些想法。

Thanks in advance, 提前致谢,

Joseph. 约瑟夫。

The latter form is more explicit about the fact that MyClass is implementing IMyClass intentionally and not by accident. 后一种形式更明确地说明了MyClass是有意而不是偶然地实现IMyClass的事实。 If that's what you intend to stress, this form is more clear. 如果这是您要强调的内容,则此表格会更清楚。 It also guards against future changes to AbstractMyClass. 它还防止将来对AbstractMyClass进行更改。 Perhaps at some point it ceases to implement IMyClass. 也许在某个时候它不再实现IMyClass。

In most cases the first form is sufficient and extra verbosity buys you nothing. 在大多数情况下,第一种形式就足够了,多余的冗长无助于您。

It is just a matter of preference. 这只是一个偏好问题。 FWIW, you can find examples for both in the JDK source: FWIW,您可以在JDK源代码中找到两个示例:

public class HashMap<K,V>
    extends AbstractMap<K,V>
    implements Map<K,V>, Cloneable, Serializable

public class ThreadPoolExecutor extends AbstractExecutorService

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM