Syntax for separating variable declaration and creating anonymous class in android / java
According to Android Studio, instead of this:
private BluetoothAdapter.LeScanCallback mCallback = new BluetoothAdapter.LeScanCallback() {
@Override
public void onLeScan(final BluetoothDevice device, int rssi, byte[] scanRecord) {
}
};
I can do it:
private BluetoothAdapter.LeScanCallback mCallback;
{
mCallback = new BluetoothAdapter.LeScanCallback() {
@Override
public void onLeScan(final BluetoothDevice device, int rssi, byte[] scanRecord) {
}
};
}
I think the second syntax is much prettier, but I don't understand why it needs curly braces around the creation of the anonymous class. I understand that curly braces locally cover closed code which doesn't make much sense to me. What am I missing?
source to share
These brackets around the field's initialization are called the initialization block . Anything you put inside is done with the constructor. You can execute any code inside 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 compilation error:
Object a = b.toString();
Object b = "";
Until it succeeds at runtime:
Object c;
Object d;
{
d = c.toString();
c = "";
}
It gets even more complicated when you add to the regular constructors and superclasses.
source to share
When using anonymous classes, you include the code for the class definition in curly braces after the new NewClass statement. This is useful when it is a one-off class that you no longer need. If you will be using this class frequently, you may need to create a separate class file to define it.
You can do the same with method definitions.
source to share