Effective Java 52 Refer to objects by their interfaces
2014-04-15 22:01 小郝(Kaibo Hao) 阅读(355) 评论(0) 编辑 收藏 举报Principle
-
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.
// Good - uses interface as type
List<Subscriber> subscribers = new Vector<Subscriber>();
-
If you depend on any special properties of an implementation, document these requirements where you declare the variable.
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.
-
It is entirely appropriate to refer to an object by a class rather than an interface if no appropriate interface exists.
Examples:
- Value classes - String, BigDecimal
- Class-based framework - java.util.TimerTask
-
Classes that implement an interface but provide extra methods not found in the interface - LinkedHashMap
Summary
In practice, it depends whether a given object has an appropriate interface. If it does, your program will be more flexible if you use the interface to refer to the object; if not, just use the least specific class in the class hierarchy that provides the required functionality.
作者:小郝
出处:http://www.cnblogs.com/haokaibo/
本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。
出处:http://www.cnblogs.com/haokaibo/
本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。