在 parent 的构造函数中使用 child 的属性

Use child's attribute in parent's constructor

class abstract Parent ()
{
     private int a;
     private final int b = a + 1; // a is null at that point
}

class Child extends Parent
{
    public Child()
    {
       a = 2;
    }
}

这在 C++ 中并不是真正的问题(因为指针),但我不确定如何在 Java 中处理这个问题。当Parent试图发起b.

时,显然a等于0

我最初尝试在设置 a 后调用 super(),但显然 super() 必须先在 child 的构造函数中调用。我不想在 Childs 中设置 b,我更希望 b 也为 final。有什么想法吗?

你想要的不能这样完成,你需要做的是将a的值传递给Parent的构造函数:

abstract class Parent {
    private int a;
    private final int b;

    protected Parent(int a) {
        this.a = a;
        b = a + 1;
    }
}

并将Child定义为:

class Child extends Parent {
    public Child() {
        super(2);
    }
}