0

So essentially having trouble understanding the uses of the 'this' keyword in java. Have read around five tutorials, albeit not very good ones. Could someone quickly explain how it's used in relation to the following code? This is an android, it's assigning an xml button (btn_confirm) to b with Button type.

   Button b = (Button)this.findViewById(R.id.btn_confirm);

b.setonclickListener(this);

Full Code:

public class dic_tut2 extends Activity implements onclickListener {

public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    Button b = (Button)this.findViewById(R.id.btn_confirm);
    b.setonclickListener(this);
}

public void onclick(View v) {

    TextView tv = (TextView)this.findViewById(R.id.tv_welcome);
    EditText et = (EditText)this.findViewById(R.id.txt_name);

    String text = "Hello, " + et.getText().toString() + ".\n\n";
    text += "Welcome to android development. :)";

    tv.setText(text);

}

}

Mark Khan
  • 73
  • 6
  • http://docs.oracle.com/javase/tutorial/java/javaOO/thiskey.html – Ben van Gompel Nov 27 '11 at 16:08
  • Have read it twice over, can make no sense of it in relation to the two lines of code I posted, nor on its own for that matter. Thanks for the response regardless. – Mark Khan Nov 27 '11 at 16:15
  • 2
    possible duplicate of [what is the meaning of "this" in java](http://stackoverflow.com/questions/3728062/what-is-the-meaning-of-this-in-java) – blank Nov 27 '11 at 16:26

3 Answers3

0

this refers to the current instance of the class where you are using it in. For example:

class A {
    public void f() {
       A obj = this; // current instance of A
    }
}

So if later I create an instance of A:

public static void main(String[] args) {

    A a = new A();
    a.f(); // the 'this' inside f() is actually 'a'.
}

So your code:

b.setonclickListener(this);

Sets the onclickListener of the button b to the current instance (the instance from which you called the method) of the class you are in.

Edit: Ok here is a complete example:

class A {
   public char c;
   public A(char c) { this.c = c; }
   public void f() {
       System.out.println(this.c);
   }
}

public static void main(String[] args) {
   A a = new A('a');
   a.f(); // prints 'a' because 'this' inside f() is actually object 'a'.

   A b = new A('b');
   b.f(); // prints 'b' because 'this' inside f() is actually object 'b'.      
}
Tudor
  • 61,523
  • 12
  • 102
  • 142
  • Hey! There's no main in an Android app! ;) – plackemacher Nov 27 '11 at 16:25
  • Ok that is not relevat, it's only for the example. It can be any method. This is also tagged as Java btw. – Tudor Nov 27 '11 at 16:25
  • Thanks for the response. My main issue with it is I just don't see why it's needed. You've used the this keyword, but I really cannot see what it does at all. I'm really sorry, it just makes no sense. – Mark Khan Nov 27 '11 at 16:25
  • @user1068042: Well think about it. Your listener has to be an instance of the current class right? If you don't use 'this' you would have to create a new instance yourself and set it as listener. But with 'this' you can just set the current object. – Tudor Nov 27 '11 at 16:27
  • What is the current object though? The statement (b.setonClickListener(this);), I'm not sure what that does, what 'this' it's referring too. I've updated my original post, and the 'this.findViewByID' I understand, as without the 'this' we'd need to create an a.findViewByID, b.fiendViewByID etc each time we use it. Is my thinking correct here? Thanks once again. – Mark Khan Nov 27 '11 at 16:34
  • When the method onClick is called, 'this' stands for the object on which it was called (whatever it is). You can see in the example in my post, if somewhere an instance of 'dic_tut2' is created, let's say 'dic', when onClick is called, 'this' actually stands for the object 'dic'. – Tudor Nov 27 '11 at 16:43
  • Didn't understand this, tried coding it out but didn't get anywhere. Would it be possible to get a quick coding example of what you mean? – Mark Khan Nov 27 '11 at 17:08
  • Thank you - I saw an example that did the same thing previously. My question with it was, would it not still print 'A' and 'B' if the 'this' part was removed? It might be because I'm not seeing the use of the A method, in my mind I see it as passing a letter into the method F, which then just prints that letter. I don't see why we would need to put it as this.c as opposed to just c in the method f. – Mark Khan Nov 27 '11 at 17:18
  • It's because 'this.c' is the same thing as saying just 'c'. In this example it's useless of course, but sometimes you need a way to refer to the object that the method was called on and that way is by using 'this'. – Tudor Nov 27 '11 at 17:20
0

In the examples you have seen, the class is most likely an activity class. Something like this:

class MainActivity extends Activity implements OnClickListener {

    @Override
    protected onCreate(Bundle bundle) {
        Button b = (Button)this.findViewById(R.id.btn_confirm);

        b.setOnClickListener(this);

    } 

    @Override
    public onClick(View v) {
        // Do something!
    }
}

This is possible because the object "this" is both an activity which can have a button in its View and it also implements OnClickListener which allows its onClick method to be called by that button when it is clicked. This is done by providing a reference to itself to the setOnClickListener function of the button.

plackemacher
  • 4,216
  • 1
  • 23
  • 26
  • Thank you for the explanation. I cannot see why the method onClick was not used inside of b.setOnClickListener, or how 'this' can refer to onClick. Is my thinking correct here or am I off the mark with regards to how the code works? – Mark Khan Nov 27 '11 at 16:45
  • Both ways can work. By using it outside of the function, it allows for easier manipulation of the Activity in the onClick function. The downside of this method is that if you want to use more than one button in the activity, you will need to check which button called the onClick function each time. – plackemacher Nov 27 '11 at 16:51
  • Do you mean by the last sentence if we use the 'this' keyword as opposed to 'onClick' inside b.setOnClickListener, we'll need to check which function called it if we have more than one button? E.g. if we have b.setOnClickListener(this) and c.setOnClickListener(this)? Or have I musjudged what you meant? Still not sure on two things, 1) How 'this' refers to onClick method in your code, and 2) What you mean by your second sentence in your last response. Apologies for the questions, I really appreciate the help. – Mark Khan Nov 27 '11 at 16:59
  • Yes, that is what I meant. For your first question: It refers to the onClick() method because when "this" is used in onCreate(), it's referring to the current object which can only be an object of MainActivity because onCreate() is in MainActivity. – plackemacher Nov 27 '11 at 18:10
0
b.setonclickListener(this);

This means the click listener for b is this: the current object. In this case, it's your Activity.

The Activity implements OnClickListener, which provides the onclick method.

You're basically saying "Button, when you're clicked, here's how to handle it--you handle it with the implementation contained within myself."

It wouldn't have to be this, it could be anything that implemented OnClickListener. By keeping the implementation local to the Activity you provide easy access to its (the Activity's) member variables (which you don't need in this case).

Inside the onclick handler the this references are superfluous--you can access the findViewById methods without the this. Member methods and variables are accessible without the qualifier.

Dave Newton
  • 158,873
  • 26
  • 254
  • 302