Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why can't I use <Class>.this in anonymous class?

I recently use this code, and realize that in anonymous class, I can't access the instance by .this, like this:

Sprite sprFace = new Sprite() {

    @Override
    protected void onManagedUpdate(float pSecondElapsed) {
        runOnUpdateThread(new Runnable() {

        @Override
        protected void run() {    
            Sprite.this.getParent().detach(Sprite.this); // Here
        }});
    }

};

I know how to solve it (just declare a "me" variable), but I need to know why I can't use <Class>.this?

like image 330
Luke Vo Avatar asked Aug 18 '11 06:08

Luke Vo


People also ask

How do you use anonymous class?

Anonymous classes enable you to make your code more concise. They enable you to declare and instantiate a class at the same time. They are like local classes except that they do not have a name. Use them if you need to use a local class only once.

How do you call an anonymous class in Java?

Object = new Example() { public void display() { System. out. println("Anonymous class overrides the method display()."); } }; Here, an object of the anonymous class is created dynamically when we need to override the display() method.

Can you have a constructor in an anonymous class?

3.1. Since they have no name, we can't extend them. For the same reason, anonymous classes cannot have explicitly declared constructors.


2 Answers

The <Class>.this syntax gives a special way of referring to the object of type <Class>, as opposed to the shadowing type.

In addition, <Class> must be the name of the type you're trying to access. In your case, Sprite is not the actual type of sprFace. Rather, sprFace is an instance of an anonymous subclass of Sprite, thus the syntax is not applicable.

like image 166
Ken Wayne VanderLinde Avatar answered Sep 25 '22 16:09

Ken Wayne VanderLinde


The type of the outer object is not Sprite, but rather an anonymous subclass of Sprite and you have no way of naming this anonymous subclass in your code.

In this case you need a name to refer to and therefore an anonymous class will not do the job. You can use a local class instead (which behaves as an anonymous class with a name). In the code block, you can write:

class MySprite extends Sprite {

    @Override
    protected void onManagedUpdate(float pSecondElapsed) {
        runOnUpdateThread(new Runnable() {
            MySprite.this.getParent().detach(MySprite.this); // Here
        });
    }

};

Sprite sprFace = new MySprite();
like image 33
Mathias Schwarz Avatar answered Sep 23 '22 16:09

Mathias Schwarz