Reputation: 11
public class Foo {
private String name;
// ...
public void setName(String name) {
// This makes it clear that you are assigning
// the value of the parameter "name" to the
// instance variable "name".
this.name = name;
}
// ...
}
Here this
keyword is acting as reference variable of current class object. But, where this object is getting created? To which object this
keyword is referencing? What'sthe logic?
Upvotes: 0
Views: 1205
Reputation: 769
The this
keyword refers to the current instance of the class. Using your class Foo here is how you can look at it:
// We create an instance of the class here
public Foo myFoo;
In your class here is what is going to happen at the high level.
public void setName(String name) {
// this.name = name;
// will be interpreted as when you call myFoo.setName(name);
// myFoo.name = name
}
You can use your debugger if you want to have an idea of how the compiler represents your objects.
Upvotes: 0
Reputation: 132
When we use the "this" refers to own class and the current instance of the class.
When programming for Android is very common to see the use of this with the class and not just attributes.
In a method of MainActivity class:
SlidingMenuAdapter slidingMenuAdapter = new SlidingMenuAdapter(MainActivity.this, listSliding);
or just
SlidingMenuAdapter slidingMenuAdapter = new SlidingMenuAdapter(this, listSliding);
Upvotes: 0
Reputation: 1500385
It's "whatever object the method was called on". We can't tell where the object is created, because that's presumably in some other code.
Have a look at this simple, complete example:
class Person {
private final String name;
public Person(String name) {
// this refers to the object being constructed
this.name = name;
}
public void printName() {
// this refers to the object the method was called on
System.out.println("My name is " + this.name);
}
}
public class Test {
public static void main(String[] args) {
Person p1 = new Person("Jon");
Person p2 = new Person("Himanshu");
p1.printName(); // Prints "My name is Jon"
p2.printName(); // Prints "My name is Himanshu"
}
}
The first time we call printName()
, we call it on the object that p1
refers to - so that's the object that this
refers to within the method, and it prints the name Jon. The second time we call printName()
, we call it on the object that p2
refers to - so that's the object that this
refers to within the method, and it prints the name Himanshu.
(It's important to note that p1
and p2
aren't objects themselves - they're variables, and the values of the variables aren't objects either, but references. See this answer for more details about that difference.)
Upvotes: 4