首页 > 解决方案 > 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 方法而不是超类中的方法。

标签: javainheritance

解决方案


但是我不明白为什么超类构造函数在调用时会使用子类中的 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


推荐阅读