zoukankan      html  css  js  c++  java
  • 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

    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.

       

       

  • 相关阅读:
    Python【第五篇】模块、包、常用模块
    Python【第四篇】函数、内置函数、递归、装饰器、生成器和迭代器
    TCP三次握手、四次挥手
    分别用postman和python做post请求接口功能测试
    Python【第三篇】文件操作、字符编码
    Python【第二篇】运算符及优先级、数据类型及常用操作、深浅拷贝
    Python【第一篇】python安装、pip基本用法、变量、输入输出、流程控制、循环
    oracle在windows(含客户端工具pl/sql安装)下安装
    Python【初识篇】简介
    Web jsp开发自学——ajax+servlet+echarts+json+gson 实现ajax传输servlert和echarts的数据,可视化结果
  • 原文地址:https://www.cnblogs.com/haokaibo/p/use-overloading-judiciously.html
Copyright © 2011-2022 走看看