Reputation: 1041
Not a duplicate, This is a semantics question?
A professor at Columbia said it, the keyword this
, points to the current class
( See Page 21 ). I'm 99% sure this is not correct.
I would like to say it passes to a class instance
or an object
. Is there a preferred way to say what this
points to concisely.
Thanks, I just want my notes to be accurate.
Upvotes: 2
Views: 185
Reputation: 172448
From the Oracle docs:
The keyword this may be used only in the body of an instance method, instance initializer, or constructor, or in the initializer of an instance variable of a class. If it appears anywhere else, a compile-time error occurs.
...
When used as a primary expression, the keyword this denotes a value that is a reference to the object for which the instance method was invoked (§15.12), or to the object being constructed.
From the wiki:
this
Used to represent an instance of the class in which it appears. this can be used to access class members and as a reference to the current instance. The this keyword is also used to forward a call from one constructor in a class to another constructor in the same class.
Upvotes: 7
Reputation: 7486
this
is a keyword used by the OO programming languages
to refer to the instance of current class
. It implicitly fetches the the reference or the address of the object or instance of the current class.
this
in JAVA
Hope this helps
Upvotes: 0
Reputation: 15742
this
refers to the current object
.
E.g
public class MyThisTest {
private int a;
public MyThisTest() {
this(42); // calls the other constructor
}
public MyThisTest(int a) {
this.a = a; // assigns the value of the parameter a to the field of the same name
}
public void frobnicate() {
int a = 1;
System.out.println(a); // refers to the local variable a
System.out.println(this.a); // refers to the field a
System.out.println(this); // refers to this entire object
}
public String toString() {
return "MyThisTest a=" + a; // refers to the field a
}
}
Self Explanatory Output:
1
42
MyThisTest a=42
Upvotes: 1
Reputation: 4048
You can think of it as the "current class". But I like to think of it as a reference to the object instance in which the "this" is used.
So if you have class A and you create two instances, A1 and A2, when you refer to "this" in a method call executing in A2, "this" refers to the instance A2, not the class A.
Clear as mud?
Upvotes: 0