基本上,这就是我想要做的:
ClassName
{
final OtherClass field;
ClassName()
{
field = new OtherClass(this);
}
}
Run Code Online (Sandbox Code Playgroud)
Fox*_*x32 27
在构造函数体中分配最终字段是不可能的.最后一个字段需要在构造函数体,初始化列表或声明中分配:
ClassName
{
final OtherClass field = new OtherClass(); // Here
ClassName()
: field = new OtherClass(); // or here
{
}
}
Run Code Online (Sandbox Code Playgroud)
由于您无法this在初始化列表或声明中使用,因此无法执行您计划执行的操作.
Cop*_*oad 12
使用 null 安全,您可以通过final不同方式初始化字段:
声明时:
class Foo{
final int bar = 1;
}
Run Code Online (Sandbox Code Playgroud)
在构造函数参数中(初始化形式)。
class Foo {
final int bar;
// Initializing in constructor parameter.
Foo(this.bar);
}
Run Code Online (Sandbox Code Playgroud)
在初始化列表中。
class Foo {
final int bar;
// Initializer list
Foo() : bar = 1;
}
Run Code Online (Sandbox Code Playgroud)
以上两者的结合。
class Foo {
final int bar;
Foo(int value) : bar = value;
}
Run Code Online (Sandbox Code Playgroud)
使用late关键字进行延迟初始化。
class Foo {
final int bar;
// Initializing in constructor parameter.
Foo(this.bar);
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4267 次 |
| 最近记录: |