有这么一个类,类中有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 );
}
}
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 );
}
}
第一个你申明的是Collection a, 所以调用print( Collection c)
第二个你申明的是ArrayList a, 所以调用print( ArrayList a)
能否具体一点解释呢?
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();
}
print( a ); 还不是输出了This is a ArrayList主要是看接受的是哪个参数了
Collection a = new ArrayList();
ArrayList a = new ArrayList();
ArrayList:实现了List接口,功能与Vetor一样,只是没有同步机制,当然元素的访问方式为从List中继承而来,可存放任何类型的对象。
貌似LZ的程序编译通不过
也就是Collection a = new ArrayList()编译时a是Collection 类型的,跟其后面的new ArrayList()无关
也就是说这里只有重载的发生,没有覆盖,不要以覆盖的思路去考虑重载