So I have searched a lot -and by "a lot" I am mean it-, both in this website and in other ones, to realize what the keyword this does in java.

I am following tutorials these days to develop a game for Android. In these tutorials, the uploader puts "this" as a parameter but he doesn't explain why he does it.

What I know so far:

  • It can be used as a parameter (this is the part I get most confused)
  • It can be put like this Fish.this to refer to an outer class (not so sure about this one)
  • It can be used to refer to refer to outer variables (worst definition ever, I know) like this:

public class Humans{

    int name; //aka name1
    public Humans(int name){ //aka name2
        this.name = name; //the name1 = name2
    }

I'd like to have an in depth explanation of that keyword since I find it really confusing and, at the same time, it prevents me from moving on with the tutorials (please don't bother answering if your response is going to be brief, I like to have things clear in my mind because I get confused easily, especially in programming). I am stuck and your help would be much appreciated!

有帮助吗?

解决方案

Within an instance method or a constructor, this is a reference to the current object — the object whose method or constructor is being called. You can refer to any member of the current object from within an instance method or a constructor by using this.

The most common reason for using the this keyword is because a field is shadowed by a method or constructor parameter.

For example, the Point class was written like this

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

    //constructor
    public Point(int a, int b) {
        x = a;
        y = b;
    }
}

but it could have been written like this:

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

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

Each argument to the constructor shadows one of the object's fields — inside the constructor x is a local copy of the constructor's first argument. To refer to the Point field x, the constructor must use this.x.

You can find good example here(Also they will show the diffrent uses of the "this" keyword) ---> http://docs.oracle.com/javase/tutorial/java/javaOO/thiskey.html

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top