user3079316 user3079316 - 1 year ago 47
Android Question

Why is "this" used as the parameter in RelativeLayout constructor?

While creating a RelativeLayout object we write this code

RelativeLayout relativeLayout = new RelativeLayout(this);

I wanna ask why we pass "this" to the constructor?

In the documentation I found that the constructor is :

RelativeLayout(Context context)

This constructor parameter accepts an parameter of type Context but we passed "this" (which I think is the RelativeLayout object that we are creating) which is of type RelativeLayout. So wouldn't there be a mismatch or I am missing something (definitely!)

Hopefully this would also answer another question of mine about how to meaningfully understand the API

Answer Source

You are mistaken, this does not refer to RelativeLayout. It refers to the class from whose method it was called (Activity, in your case).

This is from java docs:

this is a keyword in Java. It can be used inside the Method or constructor of Class. It(this) works as a reference to the current Object whose Method or constructor is being invoked. The this keyword can be used to refer to any member of the current object from within an instance Method or a constructor.

In your case, this is the object that point to the Activity you're currently in. Having in mind that activity indirectly extends Context (it extends the class that extends another one which extends Context), this means that it can be used anywhere where the type Context is expected.

Here, implicit upcast is applied, and therefore you can use it like this:

RelativeLayout relativeLayout = new RelativeLayout(this);