Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trialdlpuxdzztg
8,243 Points'.this'
Hello,
I'm still not 100% sure on how the '.this' keyword works and why we need it, if someone could explain it that would be very nice!
Thanks!
2 Answers
Kourosh Raeen
23,733 PointsThe makeText()
method of the Toast class expects a Context object as the first parameter. Since the Activity class is a subclass of the Context class you can pass a reference to the current activity, which is the FunFactsActivity. The way you get a reference to the current activity instance is by using the this
keyword. We could have just used this
instead of FunFactsActivity.this
. However, there are cases where you need to use the name of the class. For example, if the line of code for creating the toast was inside the onClick
method then using this
would refer to the instance of the anonymous listener inner class and not the activity instance. In that case, we have to use FunFactsActivity.this
.
Shadi Abdelsalam
9,490 Points.this keyword means,that you are calling a field of the class.For example:
class Worker{
public String name;
public Worker(string name){
this.name = name;
}
}
Shadi Abdelsalam
9,490 PointsIn that case,you initialize a field 'name' using .this keyword,beacause the variable 'name' without .this is a constructor's argument.