Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does the keyword this reference in this code sample? [duplicate]

Tags:

java

android

public class NewPlanet extends Activity {
 @Override
 protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_add);

    ImageView marsImage = (ImageView) findViewById(R.id.imageMars);
    marsImage.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            WorldGen mars = new WorldGen("Mars", 642, 3.7);
            mars.setPlanetColonies(1);
            Toast.makeText(NewPlanet.this, "Mars Created", Toast.LENGTH_SHORT).show();
        }
    });
 }
}

What context does NewPlanet.this reference? Why does makeText from class Toast need this context? I understand the use of keyword this when referencing a class and using dot notation to access its fields and constructors as in this.field, but what about when the this keyword comes after a class reference?

like image 933
dazedviper Avatar asked Dec 09 '25 20:12

dazedviper


2 Answers

The instance NewPlanet.this represent object of NewPlanet that is an outer class. If you have used only this, it would represent the instance of anonymous class OnClickListener.

After compilation you will get something like this:

marsImage.setOnClickListener$1(new OnClickListener$1(this));

 static class OnClickListener$1 implements OnClickListener {
        private final NewPlanet ref;
        OnClickListener$1(NewPlanet ref) {
           this.ref= ref;
        }

        @Override
        public void onClick(View v) {
            WorldGen mars = new WorldGen("Mars", 642, 3.7);
            mars.setPlanetColonies(1);
            Toast.makeText(ref, "Mars Created", Toast.LENGTH_SHORT).show();
        }
    }
like image 197
Damian Leszczyński - Vash Avatar answered Dec 11 '25 09:12

Damian Leszczyński - Vash


NewPlanet.this is a reference to this of outer class. Indeed you are using this from anonymous inner class.

like image 41
AlexR Avatar answered Dec 11 '25 10:12

AlexR



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!