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,并以超链接形式标明文章原始出处,否则将 ...
随机推荐
- Mysql学习笔记(四)字符串函数
PS:终于看完了字符串函数,心都快碎了...涉及的函数真是太多了...感觉这里的字符串函数和JAVA里的基本都差不多了...基本上算是掌握了,但是想全记住那是不太可能的... 学习内容: 字符串函数的 ...
- Websocket协议的学习、调研和实现
本文章同时发在 cpper.info. 1. websocket是什么 Websocket是html5提出的一个协议规范,参考rfc6455. websocket约定了一个通信的规范,通过一个握手的机 ...
- tomcat端口被占用
这里就以win7为例进行讲解. 首先打开cmd,打开的方法很简单,在开始菜单中直接输入即可.同样也可以按下win+R打开运行,然后输入cmd即可. 在dos命令中输入以下命令查询正在被使用的端口号以及 ...
- STL --- UVA 123 Searching Quickly
UVA - 123 Searching Quickly Problem's Link: http://acm.hust.edu.cn/vjudge/problem/viewProblem.acti ...
- 甲骨文白桃花心木P6 EPPM 8.2项目点提供样本
甲骨文白桃花心木样例代码 除非明确确定,这里的示例代码不是认证或Oracle支持;它只是用于教育或测试的目的. 你必须接受 许可协议下载此示例代码. 接受 许可协议 | 下降 许可协议 的名字 ...
- Microsoft Visual Studio 2012 文档 下载地址 vs2012 中文帮助文档
https://www.microsoft.com/zh-cn/download/confirmation.aspx?id=34794 下载地址: http://download.microsoft. ...
- 解决android引用library project错误
在andriod项目中引用另一个library project时,报 The container 'Android Dependencies' references non existing libr ...
- 【C#】1.1 第1章学习要点
分类:C#.VS2015 创建日期:2016-06-14 教材:十二五国家级规划教材<C#程序设计及应用教程>(第3版) 一.配套源程序(VS2015版)的运行截图 VS2015版的配套源 ...
- 【C#进阶系列】11 事件
事件,定义了事件成员的类型允许类型或类型的实例通知其它对象发生了特定的事情. 按照我自己的理解而言,事件可以被(方法)关注,也可以被(方法)取消关注,事件发生后关注了事件的一方会了解到,并对事件做出相 ...
- C语言范例学习01
编程语言的能力追求T型. 以前学过C语言,但是只学了理论. 从今天开始,我买了本<C语言程序开发范例宝典>.我要把它通关掉. 这应该可以极大地提升我的编程能力. 第一章 基础知识 这章没太 ...