[英]Using curly braces inside object initialization block
Why is it that the function bind()
exist only when set inside scope curly braces? 为什么仅在范围大括号内设置函数
bind()
存在?
public void initialize() {
inputsAreFull = new BooleanBinding() {
{
bind();
}
@Override
protected boolean computeValue() {
return false;
}
};
}
IntelliJ automatically recommends bind()
when inside curly braces, but the function doesn't exist outside of them? IntelliJ在大括号内时会自动推荐
bind()
,但在大括号内不存在该功能吗?
This won't work: 这行不通:
public void initialize() {
inputsAreFull = new BooleanBinding() {
bind();
@Override
protected boolean computeValue() {
return false;
}
};
}
The syntax you're using is a shortcut for declaring an implementation of type BooleanBinding
. 您使用的语法是用于声明
BooleanBinding
类型的实现的快捷方式。 You're effectively inside a class declaration. 您实际上是在类声明中。
public void initialize(){
inputsAreFull = new BooleanBinding() {
// This is equivalent to a class level scope for your anonymous class implementation.
{
bind();
}
@Override
protected boolean computeValue() {
return false;
}
};
}
You can't randomly invoke methods at a class level without an initializer block. 没有初始化程序块,您不能在类级别随机调用方法。 You can test this out by writing...
您可以通过编写来测试...
class MyClass extends BooleanBinding {
bind(); // It's not gonna be very happy with you.
@Override
protected boolean computeValue() {
return false;
}
}
IDEOne with running example: http://ideone.com/EERkXB 具有运行示例的IDEOne: http ://ideone.com/EERkXB
See also What is an initialization block? 另请参见什么是初始化块?
new BooleanBinding() { ... }
introduces an anonymous child class of BooleanBinding
. new BooleanBinding() { ... }
引入了BooleanBinding
的匿名子类。
Now bind
is a protected method, hence it is not allowed to do inputsAreFull.bind()
. 现在
bind
是一个受保护的方法,因此不允许执行inputsAreFull.bind()
。
But bind may be called in the anonymous initializer block { ... }
in the child class body. 但是可以在子类主体中的匿名初始化程序块
{ ... }
中调用bind。
There is still a remark needed: as the object is not fully initialized at that moment; 还有一点需要注意:由于此时对象尚未完全初始化; the code actually being executed in the BooleanBinding constructor (compilier takes care of that), the method
bind
should not be overridable. 如果实际上是在BooleanBinding构造函数中执行的代码(由编译器负责),则方法
bind
应该不可重写。 For that one may use a private
or (here) a protected final
method. 为此,可以使用
private
或(这里) protected final
方法。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.