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. C#基本概念列举说明

    1. 关键字      在C#代码中常常使用关键字,关键字也叫保留字,是对C#有特定意义的字符串.关键字在Visual Studio 环境的代码视图中默认以蓝色显示.例如,代码中的using.name ...

  2. Python基础:数值(布尔型、整型、长整型、浮点型、复数)

    一.概述 Python中的 数值类型(Numeric Types)共有5种:布尔型(bool).整型(int).长整型(long).浮点型(float)和复数(complex). 数值类型支持的主要操 ...

  3. 重新想象 Windows 8.1 Store Apps (86) - 系统 UI 的新特性: Theme, 窗口宽度大小可变, ApplicationView, DisplayInformation

    [源码下载] 重新想象 Windows 8.1 Store Apps (86) - 系统 UI 的新特性: Theme, 窗口宽度大小可变, ApplicationView, DisplayInfor ...

  4. IIS理解

    WEB开发基础 1IIS原理 IIS的本质其实就是一个sorket的服务器,浏览器就是一个sorket的客户端,浏览器发送请求信息给IIS,IIS返回信息给浏览器显示,就这么简单. 1http.sys ...

  5. Spring核心概念之AOP

    一.AOP 的概念 AOP(Aspect Oriented Programming)的缩写,面向切面编程,主要作用就是对代码进行增强处理. 理解面向切面编程的含义:就是在不改变原有程序的基础上为代码增 ...

  6. winform(ListView及数据库连接)

    一.ListView:列表展示数据1.视图 - 在其右上方小箭头点击将视图改为Largelcon:或右键属性在外观View将其改为Details2.设置列头 - 在其右上方小箭头点击选择编辑列,然后添 ...

  7. RHEL7文件查找

    本文介绍RHEL7下which.whereis.locate.find命令的使用,重点介绍find命令的使用 which 命令:which 作用:查找命令的执行文件路径 语法:which [选项] [ ...

  8. win7 下配置Openssl

    最近刚刚装了openssl,遇到了很多问题,于是记录了下来: 我的PC环境是:系统win7,32位,Microsoft Visual Studio 2010: 下面开始安装: 1.安装前的准备:首先下 ...

  9. ASP.NET MVC 微信公共平台开发之获取用户消息并处理

    ASP.NET MVC 微信公共平台开发 获取用户消息并处理 获取用户消息 用户发送的消息是在微信服务器发送的一个HTTP POST请求中包含的,获取用户发送的消息要从POST请求的数据流中获取 微信 ...

  10. android 事件

    package com.example.yanlei.my2; import android.app.Activity; import android.content.Context; import ...