java基础篇 之 构造器内部的多态行为
2024-09-01 12:53:27
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。到这里大家应该明白了吧
最新文章
- 安卓xml颜色设置
- oracle 连接查询,和(+)符号的用法
- MySQL 创建用户 与 授权
- bzoj4627: [BeiJing2016]回转寿司
- linux mysql字符编码问题
- Linux创建新用户以及useradd adduser的区别
- html简单样式
- 最艰难的采访IT公司ThoughtWorks代码挑战——FizzBuzzWhizz游戏
- 关闭Windows 2008下面应用程序出错后的提示
- webpack 实现的多入口项目脚手架
- ZooKeeper入门搭建教程
- SQLServer之创建非聚集索引
- [数]补题ver.
- idea 自动根据屏幕代码换行
- git 删除远程分支文件夹
- yocto-sumo源码解析(二): oe-buildenv-internal
- BitmapFactory.Options
- C1控件的破解步骤
- python 实现的比特币代码 及 加密货币学习线路图及书籍资料
- 浅析JavaScript中的typeof运算符
热门文章
- AJ学IOS(20)UI之UIPickerView_点菜系统
- SpringBoot事件监听机制源码分析(上) SpringBoot源码(九)
- matlab计算相对功率
- Python openpyxl使用操作和openpyxl操作
- Serval and Parenthesis Sequence CodeForces - 1153C
- [linux] [nginx] 一键安装web环境全攻略phpstudy版,超详细!
- 引导 ARM Linux
- AWR发现TOP Event log file sequential read
- 4、flink自定义source、sink
- input type file onchange上传文件的过程中,同一个文件二次上传无效的问题。