Using the keyword “this” in java [duplicate]

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;
    }
}

Leave a Comment