Reputation: 93
Mate, I have a very simple code where I am printing "this" along with "object" of the class. As per theory "this" refers to current "object", but in my code it looks like "this" is not referring to current object. Need some guidance please
This is my output :
costructor this hash : Sandbox.Apple@1540e19d
newApple hash : Sandbox.Apple@1540e19d
this hash : Sandbox.Apple@1540e19d
costructor this hash : Sandbox.Apple@677327b6
apples hash : Sandbox.Apple@677327b6
this hash : Sandbox.Apple@1540e19d
My Question is why the last line of the output i.e.
this hash : Sandbox.Apple@1540e19d
is referring to 1540e19d
instead of 677327b6
public class ThisKeyword {
public static void main(String[] args) {
// TODO Auto-generated method stub
Apple newApple = new Apple("Green Apple");
System.out.println("newApple hash : " + newApple);
newApple.calculateQuantity();
newApple.testThis();
}
}
class Apple {
String name;
public Apple(String name) {
this.name = name;
// TODO Auto-generated constructor stub
System.out.println("costructor this hash : " + this);
}
public void calculateQuantity() {
System.out.println("this hash : " + this);
}
public void testThis() {
Apple apples = new Apple("Red Apple");
System.out.println("apples hash : " + apples);
System.out.println("this hash : " + this);
}
}
Upvotes: 0
Views: 151
Reputation: 308
It's working as it should.
You're creating two Apple objects here, newApple (created in the main method) and apples (created in testThis()).
In Apple.testThis(), the line System.out.println("this hash : " + this);
is referencing the Apple object you're calling it from which is the variable newApple
, not apples
.
Upvotes: 1
Reputation:
The last method call you make is newApple.testThis();
in which you call System.out.println("this hash : " + this);
, since you are calling the method on newApple
, then this
refers to newApple
, not apples
.
Upvotes: 0
Reputation: 739
this
refer to current instance of the defined class, mean it refers to the object whose method is being called.
The last line output is the product of newApple.testThis()
and of course it refers to newApple with 1540e19d
Upvotes: 0
Reputation: 1879
Because when you call method newApple.testThis();
, the context of this is the object newApple
which has a reference address 1540e19d
. So statement System.out.println("this hash : " + this);
should print the address 1540e19d
.
Meanwhile, statements:
Apple apples = new Apple("Red Apple");
System.out.println("apples hash : " + apples);
gave the new address of the new object apples
,which is 677327b6
.
Upvotes: 0