我试图理解为什么下面的代码总是调用"out(Object)"方法而不是更具体的"out(int | String)"方法.非常感谢解释和解决方法.
public static void main(String[] args) {
Object[] objs = new Object[]{1, 2, 3, "test1", "test2", "test3", 1000L};
for (Object o : objs) {
out(o.getClass().cast(o)); // I have also tried passing 'o' directly
// rather than casting, but that still results
// in the out(Object) method being called
}
}
private static void out(int value) {
System.out.println("integer: " + value);
}
private static void out(String value) {
System.out.println("string : " + value);
}
private static void out(Object value) {
System.out.println("object : " + value);
}
Run Code Online (Sandbox Code Playgroud)