【发布时间】:2014-11-07 04:07:31
【问题描述】:
我对 Java 中方法覆盖和重载的工作原理有基本的了解。但我的问题是为什么编译器会根据参数的编译类型搜索最具体的方法?换句话说,为什么在方法重载的情况下它会根据引用的类型而不是对象的类型进行搜索?
查看下面的示例
class Base { }
class Derived extends Base { }
class Test {
void foo(Base thing) { System.out.println("foo(Base)"); }
void foo(Derived thing) { System.out.println("foo(Derived)"); }
public static void main(String[] args) {
Test tester = new Test();
Base base = new Base();
tester.foo(base);// 1st call
base = new Derived();
tester.foo(base); // 2nd call
tester.foo(new Derived()); // 3rd call
}
}
实际输出
1st call: foo(Base)
2nd call: foo(Base)
3rd call: foo(Derived)
我期待的输出
1st call: foo(Base)
2nd call: foo(Derived)
3rd call: foo(Derived)
【问题讨论】:
-
重复 [在此处插入]。重载是基于变量静态类型的编译时问题,即#1 和#2 中的
Base base。 -
在这种情况下,多态性与方法有什么关系?这些方法只是打印传入的内容,或者具体来说,传入的是什么类型的对象!
标签: java polymorphism overloading