5

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?

Luke Vo
  • 17,859
  • 21
  • 105
  • 181

2 Answers2

4

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.

Ken Wayne VanderLinde
  • 18,915
  • 3
  • 47
  • 72
1

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();
Mathias Schwarz
  • 7,099
  • 23
  • 28