Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/batch-file/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 在对象初始化块内使用大括号_Java_Javafx - Fatal编程技术网

Java 在对象初始化块内使用大括号

Java 在对象初始化块内使用大括号,java,javafx,Java,Javafx,为什么函数绑定只存在于范围内的花括号中 public void initialize() { inputsAreFull = new BooleanBinding() { { bind(); } @Override protected boolean computeValue() { return false; } }; } IntelliJ在大括

为什么函数绑定只存在于范围内的花括号中

public void initialize() {

    inputsAreFull = new BooleanBinding() {
        {
            bind();
        }

        @Override
        protected boolean computeValue() {
            return false;
        }
    };
}
IntelliJ在大括号内自动建议绑定,但在大括号外不存在该函数

这行不通:


您正在使用的语法是声明BooleanBinding类型实现的快捷方式。实际上,您在类声明中

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;
        }
    };
}
在没有初始值设定项块的情况下,不能在类级别随机调用方法。你可以通过写

class MyClass extends BooleanBinding {
    bind(); // It's not gonna be very happy with you.

    @Override
    protected boolean computeValue() {
        return false;
    }
}
带运行示例的IDEOne:

另请参见

新布尔绑定{…}引入了布尔绑定的匿名子类

现在是一个受保护的方法,因此不允许它执行inputsravelel.bind

但是bind可以在子类主体中的匿名初始值设定项块{…}中调用


还有一点需要注意:由于对象当时没有完全初始化;BooleanBinding构造函数编译器中实际执行的代码负责这一点,方法绑定不应被重写。因此,可以使用private或protectedfinal方法。

这不是静态初始值设定项块,而是实例初始值设定项块语法规则基本相同,尽管我的措辞不好。现在修改!可能对OP感兴趣:我认为这个答案可以通过定义/解释初始化器块与ctor相比的工作原理,以及为什么在这种情况下我们必须使用ctor来增强。我认为您应该补充的要点是,您不能使用ctor,因为类是匿名的;为了创建一个ctor,您需要使用类名作为目前无法发现的方法名。初始化程序块提供了解决此问题的方法。请查找双括号初始化。挑剔:匿名类的实例初始化程序块
class MyClass extends BooleanBinding {
    bind(); // It's not gonna be very happy with you.

    @Override
    protected boolean computeValue() {
        return false;
    }
}