java - Java:从超类构造函数中的子类调用的方法
问题描述
class AA{
int x;
protected AA(){init (1008);}
protected void init(int x)
{
this.x = x;
}
}
class BB extends AA{
public BB() {
init(super.x * 2);
}
public void init(int x)
{
super.x = x+1;
}
}
public class Main {
public static void main(String[] args) {
BB tst = new BB();
System.out.println(tst.x);
}
}
我知道这段代码将打印 2019 年。但我不明白为什么超类构造函数在调用时会使用 de 子类中的 init 方法而不是超类中的方法。
解决方案
但是我不明白为什么超类构造函数在调用时会使用子类中的 init 方法而不是超类中的方法。
因为那是与正在构造的对象相关联的那个。this
在超类构造函数中是对正在构造的子类对象的引用,因此就像init
使用该引用的任何其他调用一样,它使用子类的init
.
这可能会有所帮助,请注意末尾带有注释的行 - 注释说明了这些行的输出:
class AA{
int x;
protected AA() {
System.out.println(this.getClass().getName()); // "BB"
System.out.println(this instanceof BB); // true
init(1008);
}
protected void init(int x)
{
this.x = x;
}
}
class BB extends AA{
public BB() {
init(super.x * 2);
}
public void init(int x)
{
super.x = x+1;
}
}
public class Main {
public static void main(String[] args) {
BB tst = new BB();
System.out.println(tst.x);
}
}
这是因为子类可以覆盖方法,通常最好避免从构造函数调用非final
、非方法。private
推荐阅读
- html - 具有从阴影创建的边框的剪辑路径的边框半径
- javascript - chrome扩展在开发过程中突然不再工作了
- c++ - 快速检查如何获取自定义类型的输出?
- arrays - D3.js 节点从数组中设置 bgcolor 但从不相邻
- shopify - 购买与商店购物车不同的按钮购物车
- javascript - 如何使用部分视图正确添加分页
- loops - Dart - 关于在 if 语句中执行多行处理
- heroku - 使用github在heroku中部署项目
- azure - Azure Cosmos db Gremlin elementMap()
- ios - 关于重新排序 tableView 的问题(Apple Swift 和 Xcode 11)