先看一段代码:
class TwoFunction
{
int i;
public void first(){
i=10;
System.out.println("before second() => int i = " + i);
second();
System.out.println("after second() => int i = " + i);
}
public void second (){
i=20;
first();
}
}
class first extends TwoFunction
{
public void second(){
i=67;
System.out.println("after second() => int i = " + i);
}
}
class second extends TwoFunction
{
public void second(){
i=88;
System.out.println("after second() => int i = " + i);
}
public static void main(String args[]){
TwoFunction TF = new first();//upcasting
TF.first();
}
}
output如下
---------- output ----------
before second() => int i = 10
after second() => int i = 88
after second() => int i = 88
输出完成 (耗时 0 秒) - 正常终止
改一下:
class TwoFunction
{
int i;
public void first(){
i=10;
System.out.println("before second() => int i = " + i);
second();
System.out.println("after second() => int i = " + i);
}
public void second (){
i=20;
first();
}
}
class first extends TwoFunction
{
public void second(){
i=67;
System.out.println("after second() => int i = " + i);
}
}
class second extends TwoFunction
{
public void second(){
i=88;
System.out.println("after second() => int i = " + i);
}
/++
public static void main(String args[]){
TwoFunction TF = new first();//upcasting
TF.first();
}*/
}
public class E_12
{
public static void main(String args[]){
TwoFunction TF = new first();//upcasting
TF.first();
}
}
output如下:
---------- output ----------
before second() => int i = 10
after second() => int i = 67
after second() => int i = 67
输出完成 (耗时 0 秒) - 正常终止
------------------------------------------------
我的理解是:第一段代码虽然是first的对象向上转型,但是java中总是调用它所能找到的最外层的derived class的对应方法。这里class second在最外层次,所以调用了他的second方法;第二段代码中虽然最外层的derived class还是second,但是由于在class E_12中产生的对象看不见class second,所以对该对象来说它能看见的最外层的derived class就是class first。
我想问我是:我的看法正确吗,java中是不是总是调用对象所能找到的最外层的derived class中的对应方法
(Java will always use the most-derived method it can find for the object type)