Pure Danger Tech


navigation
home

Java inheritance question

30 Mar 2007

Say that I have this class structure with an interface, an abstract base class, and a concrete class extending the base class:

interface I { }
    abstract class B implements I { }
    class C extends B { } 

My question is, is it best practice to have C also implement I? I do this entirely inconsistently, so I’m looking for a convincing argument to either always do it the same way or at least some criteria for deciding which one is best in a given situation.

My main argument for why not to do it is that it’s unnecessary – you are already implementing I through B, so this is redundant. It also makes for a more complicated type hierarchy if you look at it in an IDE as you will likely see C show up under both B and I.

My main argument for why to do it is that it documents the intention of the class. Even though C is subclassing B, its real intent is to implement the behavior defined in I. If B ever stopped implementing I, my C would have lost it’s original intent due to a change in a different class. Of course, in reality, it’s likely that if B changed in that way, a lot of other pieces of code would break as well.

I guess the tricky thing here is that inheritance is typically a very strong relationship (is-a) and while that’s still true in the abstract base class scenario, it’s kind of a weaker relationship. Usually, the base class B only exists to remove redundancy in your code, not to model some real world thing (as in C) or behavior (as in I).

Thoughts?