Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Syntax for separating variable declaration and anonymous class instantiation in android/java

Tags:

java

android

According to Android Studio, instead of doing this:

private BluetoothAdapter.LeScanCallback mCallback = new BluetoothAdapter.LeScanCallback() {

        @Override
        public void onLeScan(final BluetoothDevice device, int rssi, byte[] scanRecord) {

        }
    };

I can do this:

private BluetoothAdapter.LeScanCallback mCallback;

{
    mCallback = new BluetoothAdapter.LeScanCallback() {

        @Override
        public void onLeScan(final BluetoothDevice device, int rssi, byte[] scanRecord) {

        }
    };
}

I think the second syntax option is much prettier, but I don't understand why it requires curly braces around the anonymous class instantiation. My understanding is that curly braces locally scope the enclosed code, which doesn't make a whole lot of sense to me. What am I missing?

like image 863
WWH Avatar asked Dec 01 '25 14:12

WWH


1 Answers

Those brackets around field initialization are called initializer block. Everything you put inside is executed with constructor. You can execute any code within it:

class Main {
    int a = 1;
    int b;

    {
        b = 1;
        System.out.println("Hello World!");
    }
}

I prefer the first approach. Initializer blocks introduce unnecessary complexity and confusion. For example this is a compile error:

Object a = b.toString();
Object b = "";

While this will fail at runtime:

Object c;
Object d;

{
    d = c.toString();
    c = "";
}

It becomes even more complex when you add regular constructors and superclasses to the mix.

like image 155
Piotr Praszmo Avatar answered Dec 04 '25 06:12

Piotr Praszmo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!