java基础篇 之 构造器内部的多态行为

​ 我们来看下下面这段代码:

public class Main {
public static void main(String[] args) {
new Son(5);
}
} class Person{
void draw(){
System.out.println("person draw");
}
Person (){
System.out.println("before person draw");
draw();
System.out.println("after person draw");
}
} class Son extends Person{
private int radius = 1;
Son(int radius){
this.radius = radius;
System.out.println("son'radius="+radius);
}
@Override
void draw(){
System.out.println("son draw,radius="+radius);
}
}

我们可以来猜下,运行结果是什么呢?

before person draw
son draw,radius=0
after person draw
son'radius=5

看到这个结果有迷惑的同学吗?为什么中间会输出son draw,radius=0呢?

下面我来解释下,首先,我们知道,在创建一个子类对象时,子类构造函数执行的时候,会默认调用父类的空参构造(如果有的话,如果没有空参构造,必须显示调用)。我们将其补全就成了这样

    Son(int radius){
super();
this.radius = radius;
System.out.println("son'radius="+radius);
}

我们又知道Person的构造函数执行的时候,调用了draw();方法,其实前面也省略了默认的this,我们也将其补全

class Person{
void draw(){
System.out.println("person draw");
}
Person (){
System.out.println("before person draw");
this.draw();
System.out.println("after person draw");
}
}

看到这里不知道大家有没有明白一点?

在执行Son的构造方法时,会先调用Person类的构造函数,此时这个构造函数中,又调用了draw方法,并且是通过this调用的。这里this指向的是一个还未完全完成初始化的Son对象(因为构造Son的构造函数还未执行,此时还在执行父类的初始化),此时的radius被赋了一个默认初始值0。到这里大家应该明白了吧

最新文章

  1. 安卓xml颜色设置
  2. oracle 连接查询,和(+)符号的用法
  3. MySQL 创建用户 与 授权
  4. bzoj4627: [BeiJing2016]回转寿司
  5. linux mysql字符编码问题
  6. Linux创建新用户以及useradd adduser的区别
  7. html简单样式
  8. 最艰难的采访IT公司ThoughtWorks代码挑战——FizzBuzzWhizz游戏
  9. 关闭Windows 2008下面应用程序出错后的提示
  10. webpack 实现的多入口项目脚手架
  11. ZooKeeper入门搭建教程
  12. SQLServer之创建非聚集索引
  13. [数]补题ver.
  14. idea 自动根据屏幕代码换行
  15. git 删除远程分支文件夹
  16. yocto-sumo源码解析(二): oe-buildenv-internal
  17. BitmapFactory.Options
  18. C1控件的破解步骤
  19. python 实现的比特币代码 及 加密货币学习线路图及书籍资料
  20. 浅析JavaScript中的typeof运算符

热门文章

  1. AJ学IOS(20)UI之UIPickerView_点菜系统
  2. SpringBoot事件监听机制源码分析(上) SpringBoot源码(九)
  3. matlab计算相对功率
  4. Python openpyxl使用操作和openpyxl操作
  5. Serval and Parenthesis Sequence CodeForces - 1153C
  6. [linux] [nginx] 一键安装web环境全攻略phpstudy版,超详细!
  7. 引导 ARM Linux
  8. AWR发现TOP Event log file sequential read
  9. 4、flink自定义source、sink
  10. input type file onchange上传文件的过程中,同一个文件二次上传无效的问题。