多态中,编译看左边,运行看右边

不多逼逼,直接上代码。

代码:(我觉得我们老师给的代码好归好,但不太容易理解,我就私自改了点,顺眼多了)

class Parent{
public int myValue=100;//Parent类型的myValue=100;
public void printValue(){
System.out.println(“Parent.printvalue(),myValue=”+myValue);//Parent类型的成员函数
}
}

class Child extends Parent{
public int myValue=200;//Child类型的myValue=200;
public void printValue(){
System.out.println(“Child.printValue(),myValue=”+myValue+” “+super.myValue);//Child类型的成员函数
}
}

public class ParentChildTest{//无用的一行
public static void main(String[] args){//以下为主函数

Parent parent=new Parent();//向空间用Parent的构造函数Parent()申请了一个堆内存空间,并将地址返回给类型为Parent的parent
parent.printValue();//调用类型为Parent的地址parent的实例对象的构造函数printValue()

Child child=new Child();//向空间用Child的构造函数Child()申请了一个堆内存空间,并将地址返回给类型为Child的child
child.printValue();//调用类型为Child的地址child的实例对象的构造函数printValue()

parent=child;//将类型为Child的地址child赋值给类型为Parent的parent,注意!parent为,类型为Parent的child地址
parent.printValue();//调用类型为Parent的地址child的实例对象的构造函数printValue()

parent.myValue++;//注意!由于类型为Parent类型,访问child地址,++作用于属于Parent类型的myValue上,此时Parent的myValue=101,而Child的myValue=200
parent.printValue();//注意!由于parent此时存储的地址为child,因此Parent的printValue已经被覆盖,使用的是Child的printValue

((Child)parent).myValue++;/*还要注意!此时parent的类型由原来的Parent类型强制转换为Child类型,再去访问child时,++作用于属于Child的myValue上,此时Parent的myValue=101,而Child的myValue=201*/
parent.printValue();//再次访问parent中的child地址,输出当前Parent的myValue与Child的myValue
}
}

输出:

 

原文地址:http://www.cnblogs.com/cocotun/p/16838456.html

1. 本站所有资源来源于用户上传和网络,如有侵权请邮件联系站长! 2. 分享目的仅供大家学习和交流,请务用于商业用途! 3. 如果你也有好源码或者教程,可以到用户中心发布,分享有积分奖励和额外收入! 4. 本站提供的源码、模板、插件等等其他资源,都不包含技术服务请大家谅解! 5. 如有链接无法下载、失效或广告,请联系管理员处理! 6. 本站资源售价只是赞助,收取费用仅维持本站的日常运营所需! 7. 如遇到加密压缩包,默认解压密码为"gltf",如遇到无法解压的请联系管理员! 8. 因为资源和程序源码均为可复制品,所以不支持任何理由的退款兑现,请斟酌后支付下载 声明:如果标题没有注明"已测试"或者"测试可用"等字样的资源源码均未经过站长测试.特别注意没有标注的源码不保证任何可用性