Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using the keyword "this" in java [duplicate]

Tags:

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.

like image 789
BloodParrot Avatar asked Feb 23 '09 13:02

BloodParrot


People also ask

Why this keyword is not used in main method?

The "this" keyword is used as a reference to an instance. Since the static methods doesn't have (belong to) any instance you cannot use the "this" reference within a static method.

When should I use this keyword in Java?

The this keyword refers to the current object in a method or constructor. The most common use of the this keyword is to eliminate the confusion between class attributes and parameters with the same name (because a class attribute is shadowed by a method or constructor parameter).

What happens if I don't use this keyword in Java?

Definition and Usage If you omit the keyword in the example above, the output would be "0" instead of "5". this can also be used to: Invoke current class constructor. Invoke current class method.

What is the use of this keyword in Java stack overflow?

Every object can access a reference to itself with keyword this (sometimes called the this reference). this always refer to class non static attribute not any other parameter or local variable.


1 Answers

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;
    }
}
like image 178
Andrew Hare Avatar answered Dec 10 '22 16:12

Andrew Hare