Tricky Tricky - 5 months ago 14
Android Question

What does "this" mean?


Possible Duplicate:

Java this.method() vs method()




I've been reading some things and doing some tutorials about android java but I still dont understand what "this" means, like in the following code.

View continueButton = this.findViewById(R.id.continue_button);
continueButton.setOnClickListener(this);
View newButton = this.findViewById(R.id.new_button);
newButton.setOnClickListener(this);


Also why is it in this example that a button is not defined with Button but with View, what is the difference?

ps. Great site!! trying to learn java and got ALLOT of answers by searching here!

Answer

The this keyword is a reference to the current object. It is used to pass this instance of the object, and more.

For example, these two allocations are equal:

class Test{

    int a;

    public Test(){
        a = 5;
        this.a = 5;
    }

}

Sometimes you have a hidden field you want to access:

class Test{

    int a;

    public Test(int a){
        this.a = a;
    }

}

Here you assigned the field a with the value in the parameter a.

The this keyword works the same way with methods. Again, these two are the same:

this.findViewById(R.id.myid);
findViewById(R.id.myid);

Finally, say you have a class MyObject that has a method which takes a MyObject parameter:

class MyObject{

    public static void myMethod(MyObject object){
        //Do something
    }

    public MyObject(){
        myMethod(this);
    }

}

In this last example you passed a reference of the current object to a static method.

Also why is it in this example that a button is not defined with Button but with View, what is the difference?

In Android SDK, a Button is a subclass of View. You can request the Button as a View and cast the View to a Button:

Button newButton = (Button) this.findViewById(R.id.new_button);