有这么一个类,类中有2个重载函数print(),在main()方法中调用的时候,如果
Collection a = new ArrayList();
print( a );
调用的是:
public static void print( Collection c)
{
System.out.println("This is a Collection.");
}
而如果:
ArrayList a = new ArrayList();
print( a );
调用的将是:
public  static void print( ArrayList a)
{
System.out.println("This is a ArrayList");
}
哪位高人能告诉我原因啊?public class Interface { public static void print( Collection c)
{
System.out.println("This is a Collection.");
}

public  static void print( ArrayList a)
{
System.out.println("This is a ArrayList");
}

public static void  main( String []args)
{
Collection a = new ArrayList();
print( a );
}
}

解决方案 »

  1.   

    看你方法参数类型的申明,然后匹配啊
    第一个你申明的是Collection a, 所以调用print( Collection c)
    第二个你申明的是ArrayList a, 所以调用print( ArrayList a) 
      

  2.   

    可是两种方法不都是最后实现了一个ArrayList么?就像List list = new ArrayList();最终不是还是得到一个ArrayList对象么?
    能否具体一点解释呢?
      

  3.   

    具体的可以参见Class类匹配方法的源码private static Method searchMethods(Method[] methods,
                                            String name,
                                            Class[] parameterTypes)
        {
      Method res = null;
            String internedName = name.intern();
            for (int i = 0; i < methods.length; i++) {
        Method m = methods[i];
                if (m.getName() == internedName
    && arrayContentsEq(parameterTypes, m.getParameterTypes())
    && (res == null
        || res.getReturnType().isAssignableFrom(m.getReturnType())))
    res = m;
            } return (res == null ? res : getReflectionFactory().copyMethod(res));
        }还有Method类的public Class<?>[] getParameterTypes() {
    return (Class<?>[]) parameterTypes.clone();
        }
      

  4.   

    这道题 是迷惑你如果 改成 ArrayList a = new ArrayList(); 
    print( a );   还不是输出了This is a ArrayList主要是看接受的是哪个参数了
      

  5.   

    我想LZ一定知道根据参数的类型来选择调用哪个函数。LZ是不知道下面两句的区别:
    Collection a = new ArrayList(); 
    ArrayList a = new ArrayList(); 
    ArrayList:实现了List接口,功能与Vetor一样,只是没有同步机制,当然元素的访问方式为从List中继承而来,可存放任何类型的对象。
    貌似LZ的程序编译通不过
      

  6.   

    重载是编译时就做好的,而覆盖是运行时进行的。
    也就是Collection a = new ArrayList()编译时a是Collection 类型的,跟其后面的new ArrayList()无关
    也就是说这里只有重载的发生,没有覆盖,不要以覆盖的思路去考虑重载