Please explain “this” to me

2020-02-26 13:44发布

问题:

I've read hundreds of explanations on "this" in java and I'm really having trouble grasping it. I'm learning android and java side-by-side, I know it's harder that way but I'm enjoying it. The one thing I'm getting killed on is "this"... I'm pasting code from a tutorial below that utilizes "this" one time. I was going to just put a piece of the code but want to be as helpful as possible.

I'm looking for a good explanation of "this" that I can add to my notes. Any and all help is appreciated. Thanks in advance.

example code starts below:

import android.app.Activity;
import android.os.Bundle;
import android.widget.Toast;
import android.view.View;
import android.content.DialogInterface;
import android.app.Dialog;
import android.app.AlertDialog;

public class DialogActivity extends Activity {
    CharSequence[] items = { "Google", "Apple", "Microsoft" };
    boolean[] itemsChecked = new boolean [items.length];

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
    }

    public void onClick(View v) {
        showDialog(0);
    }

    @Override
    protected Dialog onCreateDialog(int id) {
        switch (id) {
        case 0:
            return new AlertDialog.Builder(this)
            .setIcon(R.drawable.ic_launcher)
            .setTitle("This is a dialog with some simple text...")

            .setPositiveButton("OK",
                new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int whichButton)
                    {
                        Toast.makeText(getBaseContext(),
                                "OK Clicked!", Toast.LENGTH_SHORT).show();
                    }
                }
            )
            .setNegativeButton("Cancel",
                new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int whichButton)
                    {
                        Toast.makeText(getBaseContext(),
                                "Cancel clicked!", Toast.LENGTH_SHORT).show();
                    }
                }
            )
            .setMultiChoiceItems(items, itemsChecked,
                    new DialogInterface.OnMultiChoiceClickListener() {
                        public void onClick(DialogInterface dialog,
                                int which, boolean isChecked) {
                                    Toast.makeText(getBaseContext(),
                                        items[which] + (isChecked ? " checked!":" unchecked!"),
                                        Toast.LENGTH_SHORT).show();
                    }
                }
            ).create();
        }
        return null;
    }
}

回答1:

this refers to the current Object's reference.

Read this for more understanding.

To give an example from the link:

public class Point {
    public int x = 0;
    public int y = 0;

    //constructor
    public Point(int x, int y) {
        this.x = x;
        this.y = y;
    }
}

Here, to differentiate from the x of the Point and x of the argument, you need to tell the compiler the difference. You achieve that using this. Meaning, when I write, this.x it means, the particular x belongs to the current Object, which in the case is Point.

Taking example from the code that you have provided:

AlertDialog.Builder(this)

AlertDialog.Builder() takes in a Context as a parameter in its constructor. But here, you don't do Context someContext = new Context(); and pass that as the parameter, because you simply need to pass your current Activity's Context. So you simply use this.



回答2:

Think of this as "itself". If you pass this to a method, you're simply passing an instance of the object to the method.

ie: Student is an object, as is Classroom. If I want to add a Student to the Classroom, I might tell Student to add itself to the classroom (classrooms can't find students, can they?). So, I will say student.addToClassroom(new Classroom(), this);



回答3:

The keyword this, like others have said, is just a reference to the current object. This is usually implicit, such that if you have a class as so:

class ThisExample{
    int x;
    public ThisExample(int x){
        this.x = x;
        someMethod();
        this.someMethod();
    }

    void someMethod()
    {
    ...
    }
}

Using this.x = x helps to differentiate between the member variable owned by the class and the variable being passed into the constructor. Also, calling this.someMethod() and someMethod() does exactly the same thing because the this is implied.

In Android, sometimes you will see a method with this being passed in like someMethod(this). What happens here is that this is referring to the current Activity's Context, which is just a bunch of information explaining everything about the Activity.



回答4:

Ok I'll see how I go :P

Think of a Java object (class) as an individual entity, which has certain things which define what it IS (properties) and certain things it can DO (methods)

For example, take a (very abstract) class named Machine

class Machine {
    Piston piston1;
    ArrayList<Gear> gears;

    public void addSomeNewGears(ArrayList<Gear> gears)
    {
        for(int i = 0; i < gears.size(); i++)
        {
            this.gears.Add(gears[i]);
        }    
    }
}

In the Method addSomeNewGears we actually have access to TWO Lists named gears:

  • The Machine object's current gears,
  • The new ones we want to add.

Because they are both called gears it can be ambiguous as to which one we want to access, however the new List will take priority as it is declared locally in the method.

To access the Machine's gears, we need to use the this keyword, which tells the compiler we are looking for the class's gears, not the method's

Hope this helps!



回答5:

Instance methods (those not declared static) of a class can only be executed by reference to some instance of the class. For example:

class Foo {
    public void doSomething() {
        // "this" refers to the current object
        . . .
    }
    . . .
}

// then later:
Foo aFoo = new Foo();
aFoo.doSomething(); // "this" will be equal to "aFoo" for this call

// The following is illegal:
doSomething();

// so is this:
Foo.doSomething();

Inside the method doSomething(), the variable this refers to the specific instance of Foo that was used to invoke the method (in this example, the current object referenced by aFoo).



回答6:

this is none other than the reference of current object. this will be very useful to identify that the members belongs to the current class. For example, Class Sample{ int a; Sample(int a){ this.a=a; } } "this" will differentiate current class variable and other variable