首页 > 解决方案 > 以 this 作为参数调用父构造函数

问题描述

我有一个将其子类之一作为参数的类。在构造该子类时,我希望能够this用作该参数的值:

class A(val b: B)

class B extends A(this)

但是,这无法编译

this can be used only in a class, object, or template
[error] class B extends A(this)
[error]                   ^

有没有办法解决这个问题?我很确定这样的模式可以用 Java 编写。

标签: scala

解决方案


我不太确定最后一句话:

public class MyClass {
    static class A {
        A(B b) {
            System.out.println(b.value);
        }
    }
    static class B extends A {
        String value;;
        B() {
            super(this);
            value = "x";
        }
    }
    public static void main(String args[]) {
        new B();
    }
}

给出以下错误:

/MyClass.java:10: error: cannot reference this before supertype constructor has been called
            super(this);
                  ^

this在对象本身被构造之前,没有充分的理由试图让引用脱离构造函数的范围。重构它。


推荐阅读