父类构造器调用被子类重写的方法

举报
brucexiaogui 发表于 2021/12/30 01:04:09 2021/12/30
【摘要】 父类构造器调用被子类重写的方法 一、实例   package java022;class Animals{ private String desc; public Animals(){ this.desc = getDesc(); //②、 } public String getDesc(){ retur...

父类构造器调用被子类重写的方法

一、实例

 


  
  1. package java022;
  2. class Animals{
  3. private String desc;
  4. public Animals(){
  5. this.desc = getDesc(); //②、
  6. }
  7. public String getDesc(){
  8. return "Animal";
  9. }
  10. public String toString(){
  11. return desc;
  12. }
  13. }
  14. public class Wolf extends Animals{
  15. private String name;
  16. private double weight;
  17. public Wolf(String name,double weight){
  18. this.name = name; //③、
  19. this.weight = weight;
  20. }
  21. public String getDesc(){
  22. return "Wolf[name="+ name+",weight="+weight+"]";
  23. }
  24. public static void main(String []args){
  25. System.out.println(new Wolf("老大",25)); //①、初始化Wolf对象
  26. }
  27. }

 

 

 

二、原理讲解

1、程序从①行位置开始执行,调用Wolf类对应的构造器来初始化改Wolf对象。

2、但在执行Wolf构造器里的代码之前(③行字体代码),系统会隐式执行父类无参的构造器(②行字体代码)。

3、在执行②行字体代码时,不会调用父类的getDesc()方法,而是调用Wolf类的getDesc()方法。

4、此时还没有执行③行的代码,因此name和weight两个变量还是空值。

5、因此Wolf类的getDesc()方法返回值是Wolf[name=null,weight=0.0]

6、当执行完②行代码的赋值语句之后,程序会对Wolf对象的anme、weight两个变量进行赋值,也就是说,最终得到的Wolf对象的name和weight变量的值是老大、25 ,只是desc实例变量的值是Wolf[name=null,weight=0.0]

三、分析

该程序缠身这种输出原因在于,②行代码调用的getDesc()方法是被子类重写过的方法,这样使得对Wolf对象的实例变量赋值的语句this.nam = name   this.weight = weight 在getDesc()方法之后执行,因此getDesc()方法不能测到Wolf对象的name、weight实例变量的值。

文章来源: brucelong.blog.csdn.net,作者:Bruce小鬼,版权归原作者所有,如需转载,请联系作者。

原文链接:brucelong.blog.csdn.net/article/details/76459944

【版权声明】本文为华为云社区用户转载文章,如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱: cloudbbs@huaweicloud.com
  • 点赞
  • 收藏
  • 关注作者

评论(0

0/1000
抱歉,系统识别当前为高风险访问,暂不支持该操作

全部回复

上滑加载中

设置昵称

在此一键设置昵称,即可参与社区互动!

*长度不超过10个汉字或20个英文字符,设置后3个月内不可修改。

*长度不超过10个汉字或20个英文字符,设置后3个月内不可修改。