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
?
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.
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.
3.1. Since they have no name, we can't extend them. For the same reason, anonymous classes cannot have explicitly declared constructors.
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.
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();
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