Why does the following style of code work:
BroadcastReceiver receiver = new BroadcastReceiver() {
public void onReceive(Context context, Intent intent) {
//do something based on the intent's action
}
}
I would expect it to be:
private class MyBroadcastReceiver extends BroadcastReceiver () {
public void onReceive(Context context, Intent intent) {
//do something based on the intent's action
}
}
MyBroadcastReceiver receiver = new MyBroadcastReceiver();
In the 1st code piece above, how does the compiler know that receiver is of type MyBroadcastReceiver and not BroadcastReceiver? Isn’t this ambiguous? Why is this allowed?
If I define:
BroadcastReceiver receiver2 = new BroadcastReceiver();
Now is receiver == reciver2?
EDIT:
BroadcastReceiver
http://developer.android.com/reference/android/content/BroadcastReceiver.html
This is an anonymous class declaration. See section 15.9.5 of the JLS for more details:
The type of the
receivervariable actually is justBroadcastReceiver– but the type of the object created is an instance ofContainingClass$1which extendsBroadcastReceiver.