Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Local class definitions: why does this work

Tags:

java

android

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

like image 671
Caner Avatar asked Sep 11 '26 08:09

Caner


2 Answers

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.

like image 138
Jon Skeet Avatar answered Sep 13 '26 21:09

Jon Skeet


It works because you are using an anonymous class

like image 32
michael667 Avatar answered Sep 13 '26 22:09

michael667