Search code examples
javaandroidinheritance

This and super keyword usage in android


I am new to android and java and i can not get my head around understanding why in android "this" keyword is sometimes used and not "super"?

Also how can you call parent methods without "this" or "super" keyword.

For example lets say we have

public class MainActivity extends ActionBarActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
}

public void sendMessage(View view) {
    Intent intent = new Intent(this, DisplayMessageActivity.class);
    EditText editText = (EditText) findViewById(R.id.edit_message);
    String message = editText.getText().toString();
    intent.putExtra(EXTRA_MESSAGE, message);
    this.startActivity(intent);
}

We can see that in above example MainActivety class does not have setContentView method in fact this method is defined in ActionBarActivity as

public void setContentView(int layoutResID) {
    this.getDelegate().setContentView(layoutResID);
}

So how are we able to call it without "this" or "super"?

Why does it still work if we would put "this" infront although the method is defined in parent class isnt "this" keyword meant for current scope/class.


Solution

  • How can you call parent methods without "this" or "super" keyword?

    You can without super provided that the method you call is not redefined in the "current" class, if it is redefined you may need to disambiguate the call:

    class A {
      public void f() {}
      public void h() {} 
      public void i() {} 
    }
    
    class B extends A {
      public void g() { f(); } // same as super.f()
      public void h() { h(); /* recursive call */ }
      public void i() { super.i(); /* call to inherited but "masked" */ }
    }
    

    how are we able to call it without "this" or "super"?

    this is not mandatory, when you write something in an instance method, it is read as this.something. This is why in the preceding example, the call h() is a recursive one.

    this is not scoped, it denotes the "full" object itself. super scopes what follows. this is typed with the current class, and super is the object typed as its parent class.