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

  1. 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的更多相关文章

  1. Effective Java 11 Override clone judiciously

    Principles If you override the clone method in a nonfinal class, you should return an object obtaine ...

  2. Effective Java 42 Use varargs judiciously

    Implementation theory The varargs facility works by first creating an array whose size is the number ...

  3. Effective Java 74 Implement Serializable judiciously

    Disadvantage of Serializable A major cost of implementing Serializable is that it decreases the flex ...

  4. 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 ...

  5. 《Effective Java》读书笔记 - 7.方法

    Chapter 7 Methods Item 38: Check parameters for validity 直接举例吧: /** * ...其他的被我省略了 * @throws Arithmet ...

  6. Effective Java 第三版——41.使用标记接口定义类型

    Tips <Effective Java, Third Edition>一书英文版已经出版,这本书的第二版想必很多人都读过,号称Java四大名著之一,不过第二版2009年出版,到现在已经将 ...

  7. Effective Java 目录

    <Effective Java>目录摘抄. 我知道这看起来很糟糕.当下,自己缺少实际操作,只能暂时摘抄下目录.随着,实践的增多,慢慢填充更多的示例. Chapter 2 Creating ...

  8. 【Effective Java】阅读

    Java写了很多年,很惭愧,直到最近才读了这本经典之作<Effective Java>,按自己的理解总结下,有些可能还不够深刻 一.Creating and Destroying Obje ...

  9. [Effective Java]第八章 通用程序设计

    声明:原创作品,转载时请注明文章来自SAP师太技术博客( 博/客/园www.cnblogs.com):www.cnblogs.com/jiangzhengjun,并以超链接形式标明文章原始出处,否则将 ...

随机推荐

  1. 直接拿来用!最火的iOS开源项目

    1. AFNetworking 在众多iOS开源项目中,AFNetworking可以称得上是最受开发者欢迎的库项目.AFNetworking是一个轻量级的iOS.Mac OS X网络通信类库,现在是G ...

  2. sitemesh学习笔记(2)

    之前我也是通过网上一些资料来学习sitemesh的,后来发现那些资料都比较老了,现在最近的已经是sitemesh3了而我之前看的是sitemesh2.3,今天重新去看了一些sitemesh3的资料,发 ...

  3. TinyFox在VS2015上的调试器

    这个一个TinyFox在VS2015上的调试工具 : 开源了 https://github.com/maxzhang1985/TinyFoxDEBUG 开发这个工具的初衷,是想更便捷的调试Nancy ...

  4. XML to Entity

    public static T GetEntityByXml<T>(string xml, string rootNode=null) where T : new() { if (stri ...

  5. Brute Force & STL --- UVA 146 ID Codes

     ID Codes  Problem's Link:http://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&a ...

  6. Oracle工程建设行业解决方案

    为何选择Oracle工程建设行业解决方案? Oracle为工程建设企业提供一套全面.开放且集成的业务管理软件.服务器和存储解决方案.这些解决方案经过集成设计,能够实现卓越性能,从而优化业务的方方面面. ...

  7. android studio...混淆打包全揭秘

    前言,当前android studio使用的版本较新,低版本的如果有差异,或者问题,欢迎拍砖! 1.修改配置文件 找到配置文件,build.gradle,修改如下.    signingConfigs ...

  8. MVC 5 + EF6 入门完整教程14 -- 动态生成面包屑导航

    上篇文章我们完成了 动态生成多级菜单 这个实用组件. 本篇文章我们要开发另一个实用组件:面包屑导航. 面包屑导航(BreadcrumbNavigation)这个概念来自童话故事"汉赛尔和格莱 ...

  9. spring中常用工具类介绍

    http://www.cnblogs.com/langtianya/p/3875103.html 文件资源操作     Spring 定义了一个 org.springframework.core.io ...

  10. ASP.NET本质论第一章网站应用程序学习笔记3-对象化的Http

    在.NET环境下,万物皆对象,在HttpRuntime收到请求之后,立即将通过HttpWorkerRequest传递的参数进行分析和分解,创建方便用于网站应用程序处理用的对象,其中主要涉及到两个对象类 ...