开发者

Local class definitions: why does this work

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 rec开发者_如何学运维eiver2 = 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


You are creating here an unnamed class, which extends BroadcastReciever. This is usual in Java e.g. to create Listeners. As the unnamed class extends BroadcastReciever it can be used by a reference of that type.


This is called an anonymous inner class. As this name indicates, such a class has no name.

It will be compiled to a .class file name EnclosingClass$1.class. The class file of the receiver2 variable will be EnclosingClass$2.class.


In the first example, the class receiver is NOT an instance of MyBroadcastReceiver; it is an anonymous instance of BroadcastReceiver.

BroadcastReceiver receiver = new BroadcastReceiver() {
    public void onReceive(Context context, Intent intent) {

    }
}

MyBroadcastReceiver myReceiver = new MyBroadcastReceiver();

(receiver instanceof MyBroadcastReceiver); // is FALSE
(receiver instanceof BroadcastReceiver); // is TRUE


In the 1st code piece above, how does the compiler know that receiver is of type MyBroadcastReceiver and not BroadcastReceiver?

It does not, you simply created an instance of an anonymous class extending BroadcastReceiver with a specific implementation.

Now is receiver == reciver2?

Clearly no: they are two distinct instances (even though they both extend BroadcastReceiver).

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜