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.
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.
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).
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.
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.
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;
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With