Java – Programming against interfaces in Java

interfacesjavastatic methods

Supposing I have an interface Foo and a given implementation FooImpl.

public class FooImpl implements Foo

If I want to define a new operation on this class that depends on the particular implementation, is it correct to define it in the implementation class or as a static method on an Util class like FooUtils.operation?

public class FooImpl {
  public void operation() {
    ...
  }
}

public class FooUtils {
  public static void operation(Foo f) {
    ...
  }
}

The first option forces me to cast to the given implementation class whenever I want to use it on an object that is declared of the type of the interface (it is good practice to program against interfaces). For example:

Foo f = FooImpl.newInstance();
((FooImpl) f).operation();

which is a bit ugly.

The second option doesn't have this problem but it is not very pretty either:

FooUtils.operation(f)

Best Answer

If not every implementer of Foo is supposed to contain operation(), then operation() cannot be declared in Foo, plain and simple.

Programming against interfaces rather than concrete classes is a good idea, but only if the interface actually is sufficient for your needs. If you need to call operation(), then you should declare FooImpl, or maybe a custom subinterface of Foo, but never Foo. That would completely subvert the point of using an interface: not having to know concrete subclasses.

Related Topic