3
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?

dazedviper
  • 992
  • 1
  • 9
  • 17

3 Answers3

3

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();
        }
    }
2

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

AlexR
  • 114,158
  • 16
  • 130
  • 208
0

It's a reference to the NewPlanet that the onCreate() method is called on

Nathan Adams
  • 1,255
  • 1
  • 11
  • 17