Item 52: Refer to objects by their interfaces

1.  If appropriate interface types exist, then parameters, return values, variables, and fields should all be declared using interface types. The only time you really need to refer to an object’s class is when you’re creating it with a constructor.

 

2.  If you get into the habit of using interfaces as types, your program will be much more flexible. If you decide that you want to switch implementations, all you have to do is change the class name in the constructor (or use a different static factory).

 

3.  There is one caveat: if the original implementation offered some special functionality not required by the general contract of the interface and the code depended on that functionality, then it is critical that the new implementation provide the same functionality. If you depend on any special properties of an implementation, document these requirements where you declare the variable.

 

4.  It is entirely appropriate to refer to an object by a class rather than an interface if no appropriate interface exists.(For example, value classes such as String and BigInteger.)

 

5.  A class that implements an interface but provides extra methods not found in the interface for example, LinkedHashMap should be used to refer to its instances only if the program relies on the extra methods.

 

你可能感兴趣的:(interface,implementation)