Effective Java 41 Use overloading judiciously
The choice of which overloading to invoke is made at compile time.
// Broken! - What does this program print?
public class CollectionClassifier {
public static String classify(Set<?> s) {
return "Set";
}
public static String classify(List<?> lst) {
return "List";
}
public static String classify(Collection<?> c) {
return "Unknown Collection";
}
public static void main(String[] args) {
Collection<?>[] collections = {
new HashSet<String>(),
new ArrayList<BigInteger>(),
new HashMap<String, String>().values()
};
for (Collection<?> c : collections)
System.out.println(classify(c));
// the result will prints three times "Unknown Collection"
}
}
Selection among overloaded methods is static, while selection among overridden methods is dynamic.
The compile-time type of an object has no effect on which method is executed when an overridden method is invoked; the "most specific" overriding method always gets executed.
class Wine {
String name() { return "wine"; }
}
class SparklingWine extends Wine {
@Override String name() { return "sparkling wine"; }
}
class Champagne extends SparklingWine {
@Override String name() { return "champagne"; }
}
public class Overriding {
public static void main(String[] args) {
Wine[] wines = {
new Wine(), new SparklingWine(), new Champagne()
};
for (Wine wine : wines)
System.out.println(wine.name());
// This will print "wine" "sparking wine" "Champagne"
}
}
Principle
- A safe, conservative policy is never to export two overloadings with the same number of parameters.
public class SetList {
public static void main(String[] args) {
Set<Integer> set = new TreeSet<Integer>();
List<Integer> list = new ArrayList<Integer>();
for (int i = -3; i < 3; i++) {
set.add(i);
list.add(i);
}
for (int i = 0; i < 3; i++) {
set.remove(i);
list.remove(i);
}
System.out.println(set + " " + list);
// This will prints [-3, -2, -1] [-2, 0, 2]
}
}
The call to set.remove(i)selects the overloading remove(E), where E is the element type of the set (Integer), and autoboxes I from int to Integer.
The call to list.remove(i), on the other hand, selects the overloading remove(int i), which removes the element at the specified position from a list.
2. The standard way to ensure behavior of the types of the same super class or interface as the parameter of a method is to have the more specific overloading forward to the more general.
public boolean contentEquals(StringBuffer sb) {
return contentEquals((CharSequence) sb);
}
Summary
You should generally refrain from overloading methods with multiple signatures that have the same number of parameters. You can name the method with same prefix rather than overloading the write method. Such as, these variants of ObjectOutputStream have signatures like writeBoolean(boolean), writeInt(int), and writeLong(long).
In some cases, especially where constructors are involved, it may be impossible to follow this advice. In that case, you should at least avoid situations where the same set of parameters can be passed to different overloadings by the addition of casts. In this case you have the option of exporting static factories instead of constructors (Item 1).
If such a situation cannot be avoided, for example, because you are retrofitting an existing class to implement a new interface, you should ensure that all overloadings behave identically when passed the same parameters.
Effective Java 41 Use overloading judiciously的更多相关文章
- Effective Java 11 Override clone judiciously
Principles If you override the clone method in a nonfinal class, you should return an object obtaine ...
- Effective Java 42 Use varargs judiciously
Implementation theory The varargs facility works by first creating an array whose size is the number ...
- Effective Java 74 Implement Serializable judiciously
Disadvantage of Serializable A major cost of implementing Serializable is that it decreases the flex ...
- Effective Java Index
Hi guys, I am happy to tell you that I am moving to the open source world. And Java is the 1st langu ...
- 《Effective Java》读书笔记 - 7.方法
Chapter 7 Methods Item 38: Check parameters for validity 直接举例吧: /** * ...其他的被我省略了 * @throws Arithmet ...
- Effective Java 第三版——41.使用标记接口定义类型
Tips <Effective Java, Third Edition>一书英文版已经出版,这本书的第二版想必很多人都读过,号称Java四大名著之一,不过第二版2009年出版,到现在已经将 ...
- Effective Java 目录
<Effective Java>目录摘抄. 我知道这看起来很糟糕.当下,自己缺少实际操作,只能暂时摘抄下目录.随着,实践的增多,慢慢填充更多的示例. Chapter 2 Creating ...
- 【Effective Java】阅读
Java写了很多年,很惭愧,直到最近才读了这本经典之作<Effective Java>,按自己的理解总结下,有些可能还不够深刻 一.Creating and Destroying Obje ...
- [Effective Java]第八章 通用程序设计
声明:原创作品,转载时请注明文章来自SAP师太技术博客( 博/客/园www.cnblogs.com):www.cnblogs.com/jiangzhengjun,并以超链接形式标明文章原始出处,否则将 ...
随机推荐
- API Design
REST API Design Guidelines V 1.0.201208 Draft 5 Last Updated: 08/31/2012 1 简介 本文档旨在规范REST API的 ...
- IOS开发UI基础UISwitch属性
UISwitch属性1. onTintColor 处于on时switch 的颜色 switchImage.onTintColor = [UIColor grayColor];2.tintC ...
- angular设置title
Javascript框架在处理seo方面存在问题,因为爬虫在检索seo信息的时候会读不了js给其赋的值,导致搜索引擎收录不了或者收录了无效的信息,比如收录的可能是title={{title}}这样的, ...
- C#入门经典第五版之变量与表达式编码题训练
问题:编写一个控制台应用程序,要求用户输入4个int值,并显示它们的乘积.提示:可以使用Convert.ToDouble()命令,把用户在控制台上输入的数转换为double, 以此类推,转换成int命 ...
- MVC。Action方法,常用的返回类型有几种?
常用的: 1,string,直接返回响应报文字符串 public ActionResult test(){return "哈哈";}2.ViewResult,ActionResul ...
- 无意中在sql日志中发现如下内容,
日期,源,严重性,消息01/06/2015 09:06:13,登录,未知,Length specified in network packet payload did not match number ...
- 重构第26天 移除双重否定(Remove Double Negative)
理解:”移除双重否定”是指把代码中的双重否定语句修改成简单的肯定语句,这样即让代码可读,同时也给维护带来了方便. 详解:避免双重否定重构本身非常容易实现,但我们却在太多的代码中见过因为双重否定降低了代 ...
- AEAI WM V1.0 工作管理系统开源发版
AEAI WM工作管理系统是沈阳数通畅联软件公司基于AEAI DP平台开发的开源Java Web系统,用来管理记录日常工作内容及周工作内容等事务,AEAI WM工作管理系统包括一些核心的工作管理业务功 ...
- Azure开发者任务之七:在Azure托管服务中托管WCF服务角色
在一个托管服务中托管一个WCF服务角色和托管一个ASP.Net Web Role基本类似. 在上一篇文章中,我们学习了如何使用WCF Service Web Role. 在本文中,我会对上一篇文章进行 ...
- Dev-Cpp配置OpenGL图形库(成功版本:Dev-Cpp 5.7.1 MinGW 4.8.1)
★配置前须知:Dev-Cpp自带OpenGL的使用和OpenGL简介 (附Dev-Cpp下载地址:http://sourceforge.net/projects/orwelldevcpp/?sourc ...