Using the keyword “this” in java [duplicate]

2019-01-01 10:59发布

This question already has an answer here:

I'm trying to get an understanding of what the the java keyword this actually does. I've been reading Sun's documentation but I'm still fuzzy on what this actually does.

标签: java keyword
12条回答
泪湿衣
2楼-- · 2019-01-01 11:40

The keyword this can mean different things in different contexts, that's probably the source of your confusion.

It can be used as a object reference which refers to the instance the current method was called on: return this;

It can be used as a object reference which refers to the instance the current constructor is creating, e.g. to access hidden fields:

MyClass(String name)
{
    this.name = name;
}

It can be used to invoke a different constructor of a a class from within a constructor:

MyClass()
{
    this("default name");
}

It can be used to access enclosing instances from within a nested class:

public class MyClass
{
    String name;

    public class MyClass
    {
        String name;

        public String getOuterName()
        {
            return MyClass.this.name;
        }
    }
}
查看更多
泛滥B
3楼-- · 2019-01-01 11:43

"this" keyword refers to current object due to which the method is under execution. It is also used to avoid ambiguity between local variable passed as a argument in a method and instance variable whenever instance variable and local variable has a same name.

Example ::

public class ThisDemo1 
{
    public static void main(String[] args) 
   {
        A a1=new A(4,5);       
   }
}

class A
{
    int num1;
    int num2;

    A(int num1)
    {
        this.num1=num1; //here "this" refers to instance variable num1. 
       //"this" avoids ambigutiy between local variable "num1" & instance variable "num1"

        System.out.println("num1 :: "+(this.num1));
    }

    A(int num, int num2)
    {
        this(num); //here "this" calls 1 argument constructor within the same class.
        this.num2=num2;
        System.out.println("num2 :: "+(this.num2)); 
       //Above line prints value of the instance variable num2.
    }
}
查看更多
看淡一切
4楼-- · 2019-01-01 11:48

What 'this' does is very simply. It holds the reference of current object.

  • This keyword holds the reference of instance of current class
  • This keyword can not be used inside static function or static blocks
  • This keyword can be used to access shadowed variable of instance
  • This keyword can be used to pass current object as parameter in function calls
  • This keyword can be used to create constructor chain

Source: http://javaandme.com/core-java/this-word

查看更多
情到深处是孤独
5楼-- · 2019-01-01 11:50

The this keyword is a reference to the current object.

class Foo
{
    private int bar;

    public Foo(int bar)
    {
        // the "this" keyword allows you to specify that
        // you mean "this type" and reference the members
        // of this type - in this instance it is allowing
        // you to disambiguate between the private member
        // "bar" and the parameter "bar" passed into the
        // constructor
        this.bar = bar;
    }
}

Another way to think about it is that the this keyword is like a personal pronoun that you use to reference yourself. Other languages have different words for the same concept. VB uses Me and the Python convention (as Python does not use a keyword, simply an implicit parameter to each method) is to use self.

If you were to reference objects that are intrinsically yours you would say something like this:

My arm or my leg

Think of this as just a way for a type to say "my". So a psuedocode representation would look like this:

class Foo
{
    private int bar;

    public Foo(int bar)
    {
        my.bar = bar;
    }
}
查看更多
零度萤火
6楼-- · 2019-01-01 11:51

The keyword this is a reference to the current object. It's best explained with the following piece of code:

public class MyClass {

    public void testingThis() 
    {
        // You can access the stuff below by 
        // using this (although this is not mandatory)

        System.out.println(this.myInt);
        System.out.println(this.myStringMethod());

        // Will print out:
        // 100
        // Hello World
    }

    int myInt = 100;
    string myStringMethod() 
    {
        return "Hello World";
    }

}

It's not used a lot unless you have code standard at your place telling you to use the this keyword. There is one common use for it, and that's if you follow a code convention where you have parameter names that are the same as your class attributes:

public class ProperExample {
    private int numberOfExamples;

    public ProperExample(int numberOfExamples) 
    {
        this.numberOfExamples = numberOfExamples;
    }
}

One proper use of the this keyword is to chain constructors (making constructing object consistent throughout constructors):

public class Square {
    public Square() 
    {
        this(0, 0);
    }

    public Square(int x_and_y) 
    {
        this(x_and_y, x_and_y);
    }

    public Square(int x, int y)
    {
       // finally do something with x and y
    }
}

This keyword works the same way in e.g. C#.

查看更多
倾城一夜雪
7楼-- · 2019-01-01 11:58

The keyword 'this' refers to the current object's context. In many cases (as Andrew points out), you'll use an explicit this to make it clear that you're referring to the current object.

Also, from 'this and super':

*There are other uses for this. Sometimes, when you are writing an instance method, you need to pass the object that contains the method to a subroutine, as an actual parameter. In that case, you can use this as the actual parameter. For example, if you wanted to print out a string representation of the object, you could say "System.out.println(this);". Or you could assign the value of this to another variable in an assignment statement.

In fact, you can do anything with this that you could do with any other variable, except change its value.*

That site also refers to the related concept of 'super', which may prove to be helpful in understanding how these work with inheritance.

查看更多
登录 后发表回答