Java开发网 Java开发网
注册 | 登录 | 帮助 | 搜索 | 排行榜 | 发帖统计  

您没有登录

» Java开发网 » Java SE 综合讨论区  

按打印兼容模式打印这个话题 打印话题    把这个话题寄给朋友 寄给朋友    该主题的所有更新都将Email到你的邮箱 订阅主题
flat modethreaded modego to previous topicgo to next topicgo to back
作者 关于derived class 中的被覆写方法的调用
AchillesA

  very com



发贴: 35
积分: 0
于 2004-08-06 17:05 user profilesend a private message to usersearch all posts byselect and copy to clipboard. 
ie only, sorry for netscape users:-)add this post to my favorite list
先看一段代码:

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)




初学者与<书>

话题树型展开
人气 标题 作者 字数 发贴时间
2741 关于derived class 中的被覆写方法的调用 AchillesA 2243 2004-08-06 17:05

flat modethreaded modego to previous topicgo to next topicgo to back
  已读帖子
  新的帖子
  被删除的帖子
Jump to the top of page

   Powered by Jute Powerful Forum® Version Jute 1.5.6 Ent
Copyright © 2002-2021 Cjsdn Team. All Righits Reserved. 闽ICP备05005120号-1
客服电话 18559299278    客服信箱 714923@qq.com    客服QQ 714923