Java Interfaces – Should You Implement an Interface Directly or Have the Superclass Do It?

abstract classinterfacesjava

Is there a difference between

public class A extends AbstractB implements C
{...}

versus…

public class A extends AbstractB
{...}
abstract class AbstractB implements C
{...}

I understand that in both cases, class A will end up conforming to the interface. In the second case, AbstractB can provide implementation for interface methods in C. Is that the only difference?

If I do NOT want to provide an implementation for any of the interface methods in AbstractB, which style should I be using? Does using one or the other have some hidden 'documentation' purpose?

Best Answer

It all depends on if AbstractB implements C semantically. I.e if it makes sense semantically for AbstractB to implement C, then go for it.

If we take concrete examples the semantic difference becomes clear.

If A = Dog , AbstractB = Animal, C = IBark

Only choice that makes sense is

class Dog extends Animal implements IBark{

This makes no sense, since this would imply that all animals bark.

class Animal implements IBark{

The other differences come into play if you have more than just class A inheriting from AbstractB. In #1 they need not implement C, in #2 they are all forced to implement C.

Related Topic