开发者

Syntax question - extending abstract classes that implement an interface

开发者 https://www.devze.com 2023-02-03 14:08 出处:网络
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:

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:

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:

public class MyClass extends AbstractMyClass {
}

and

public class MyC开发者_如何转开发lass 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. If that's what you intend to stress, this form is more clear. It also guards against future changes to AbstractMyClass. Perhaps at some point it ceases to implement 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:

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

public class ThreadPoolExecutor extends AbstractExecutorService
0

精彩评论

暂无评论...
验证码 换一张
取 消