scala - 以 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 编写。
解决方案
我不太确定最后一句话:
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
在对象本身被构造之前,没有充分的理由试图让引用脱离构造函数的范围。重构它。
推荐阅读
- c# - 汽车没有倒在地上
- javascript - 网络中的firebase google身份验证不适用于android应用程序webview
- android - 迁移到 androidx:java.lang.ClassNotFoundException: at dalvik.system.BaseDexClassLoader.findClass 后播放控制台上的错误
- qt - Qt Installer Framework:如何检查是否选择了组件进行安装
- html - 移动和桌面上的 Boostrap 4 Grid System
- angularjs - 如何使用正文发送 angularjs $http GET 请求
- python - Keras vs PyTorch LSTM 不同的结果
- azure-application-insights - 有没有办法通知 Application Insights 有关路由结构的信息?
- java - 重载时equals方法的行为如何?
- python - python:在数据帧范围内填充元组中的元组