一旦你创建了一个Child
类型的对象,那就是它的运行时类型。这不会改变,无论演员是什么,也不管你做什么。当你调用一个方法时,这个运行时类型的实现将被执行。如果该类型没有自己的实现,它将委派给父类。
即使您调用Parent
中定义的method1
,一旦该方法调用method2
它将解析为实现对象的运行时类型。如果这是Child
,那么这就是将要调用的类的方法。
请注意,此动态行为与选择基于参数类型的静态方法不同。采取以下,与您的类定义...
public void methodTest(Parent p) {} //Let's call this "first method"
public void methodTest(Child c) {} //Let's call this "second method"
Parent p = new Parent();
Child c = new Child();
//Assume a is a variable of some type that implements the above methods
a.methodTest(p); //Will call first method
a.methodTest(c); //Will call second method
a.methodTest((Parent)c); //WILL CALL FIRST METHOD!
所以选择一个基于参数类型的方法是静态完成。它不会根据运行时类型选择不同的方法。
但是,根据它被调用的对象来选择方法取决于该对象的运行时类型。这就是允许我们覆盖子类中的方法行为的原因。
为什么不通过调试器运行代码并包含一些'println'语句? – mre
为什么不直接在测试程序中快速实现并找出? – Tudor
写一个学习测试,并找出:http://users.csc.calpoly.edu/~djanzen/tdl/learningtest/ –