Java Interface Implementation – Should a Class Explicitly Implement an Interface if Its Superclass Does?

coding-stylejava

Given an interface

interface I {
    one();
    two();
}

An abstract base class partially implementing I

abstract class A {
    @Override
    void one() {
         //something
    }
}

And lastly a subclass of A

class B extends A (implements I) {
     @OVerride
     void two() {
         //something
    }
}

And now B has to implement I since A did.

In the B class I have (implements I) and my question is,
is it good coding style to explicitly mention that you implement I?
Even though that's given implicitly by the fact that you're subclassing A, that's partially implementing I?

Please note this is a question about good style. I know there is no difference between the two approaches, language-wise.

Best Answer

While I don't have an authoritative answer, in my experience it would depend on the situation.

Usually, the redundancy is unneeded. The main point here is readability, and shorter is typically better. And, as you've already mentioned in the question, there's no functional difference, so write whichever one better fits the logic of the model and will make it easier to understand.

From time to time, including the redundant interface can be useful. Here's a version (using the Animal->Cat classes) of one time I left it in:

interface Animal {}
interface DomesticAnimal implements Animal {}

abstract class AbstractMammal implements Animal {}
class ConcreteDolphin extends AbstractMammal {}
abstract class AbstractCat extends AbstractMammal implements Animal {}
class DomesticCat extends AbstractCat implements DomesticAnimal {}
class WildCat extends AbstractCat {}

A bit of context: In that particular case my task was to implement some new functionality in the new ConcreteDolphin and AbstractMammal classes and refactor a bit of common code in the abstract class.

However, my team was already used to working with Animals, and AbstractMammals were still a fairly new concept. After all, everyone knows that a Cat must be an Animal; what was this AbstractMammal nonsense?!

Thus in this case I thought it was better to leave the redundant AbstractCat extends AbstractMammal implements Animal as it made it easier to read. I'd say this is a somewhat rare case, though, most times it would be cleaner to only have the one.