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:
An anonymous class declaration is automatically derived from a class instance creation expression by the compiler.
The type of the receiver variable actually is just BroadcastReceiver - but the type of the object created is an instance of ContainingClass$1 which extends BroadcastReceiver.
It works because you are using an anonymous class
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With