简体   繁体   中英

Using curly braces inside object initialization block

Why is it that the function bind() exist only when set inside scope curly braces?

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?

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 . 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

See also What is an initialization block?

new BooleanBinding() { ... } introduces an anonymous child class of BooleanBinding .

Now bind is a protected method, hence it is not allowed to do inputsAreFull.bind() .

But bind may be called in the anonymous initializer block { ... } in the child class body.

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. For that one may use a private or (here) a protected final method.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM