Search code examples
javainterfacedynamic-binding

Effective Java item 19- only using interfaces to define types


I have an abstract class which implements two interfaces. Am I right in thinking Because I use two interfaces, I cannot use either interface to implement dynamic binding? Reason being if I were to use one of the interfaces, I would obviously not be able to invoke methods from the other interface as the type system would only allow the sub type to invoke methods defined by the interface I used to declare the polymorphic variable?

Therefore, my actual question is it ok that I am only really using the interfaces to ensure my abstract class (or the subclasses) definitely provide an implementation for the methods? This seems to contradict what Item 19 states- you should only use interfaces for types (I took that to mean polymorphism).

Example:

public interface A{
    public void meth1();
}

public interface B{
    public void meth2();
}

public abstract class C implements A,B{

}

public void DynamicBinding(A aobject){
  //Can only call aobject.meth1();
}

Solution

  • When you need methods from only A then A can be used as an object's type as you have illustrated. Similarly for B. If you need methods from both, you make make a new interface:

    public interface C extends A, B {
    }
    

    Interfaces are allowed to extend more than one interface.

    Then you can add an abstract class with default implementations, if you wish:

    public abstract class D implements C {
      // implementation details
    }