0

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 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.

2 Answers 2

2

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.

Sign up to request clarification or add additional context in comments.

Comments

1

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

4 Comments

Note that Josh Bloch has said (don't remember where I saw it, sorry) that in cases such as HashMap there, he doesn't think the implements Map<K,V> adds much and he would leave it off if he were doing it again.
Would he have to do it again? What happens if the next JDK release dropped the implements clause? It would still be binary and source compatible (since the implements is implied anyway), right?
Does an explicit implements make instanceof calls (ever so slightly) faster?
I think the big difference is about inheritance. Without implementing interface, from a child class, u can't do things like: Map map = new HashMap(...), this also means u can't take advantage of polymorphism. So you can see why class HashMap implements Map.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.