From Effective Java 2/e by Joshua Bloch
If appropriate interface types exist, then parameters, return values, variables, and fields should all be declared using interface types.
// Good - uses interface as type List<Subscriber> subscribers = new ArrayList<Subscriber>(); List<Subscriber> subscribers = new Vector<Subscriber>(); // Bad - uses class as type! Vector<Subscriber> subscribers = new Vector<Subscriber>();
- If you get into the habit of using interfaces as types, your program will be much more flexible.
- Declaring the field with the interface type “keeps you honest.”
No appropriate interface to refer
- It is entirely appropriate to refer to an object by a class rather than an interface if no appropriate interface exists.
- If an object belongs to such a class-based framework, it is preferable to refer to it by the relevant base class, which is typically abstract, rather than by its implementation class.
There is no appropriate interface type is that of classes that implement an interface but provide extra methods not found in the interface.
If you depend on any special properties of an implementation, document these requirements where you declare the variable.