Before Marking this as duplicate please read the question once. I have read the question related to this
from here already.
I have two java class Test2 and Test as given below. As far as I understand this
refers to current object and can be used inside constructors
, non-static methods
and various other places as given in other question (link given above). But when I am initialising the instance variable in Test2 using this
:
- Which object it refers to, if it refers to currently calling object, why it is not printing
Hello World!
? - If not, then which object is being referred here and how does it get passed to instance variable ?
Class Test2.java
public class Test2 {
private String test2Str;
private Test test = new Test(this);//Please notice the instance variable init
public Test2(String str){
this.test2Str = str;
}
public Test getTest() {
return test;
}
public String getStr() {
return this.test2Str;
}
public void setTest(Test test) {
this.test = test;
}
public static void main(String[] args){
Test2 object = new Test2("Hello World!");
String thisStr = object.getTest().getStr();
System.out.println(thisStr);
}
}
Class Test.java
public class Test {
String str;
public Test(Test2 test){
System.out.println(test);
System.out.println(test.getStr());
str = test.getStr();
}
public void setStr(String str){
this.str = str;
}
public String getStr(){
return this.str;
}
}
First Output of the program :
com.avnet.spoj.lifeuniverse.Test2@56e5b723
null
null
Note : If I move instance variable initialisation inside constructor as given below. It works as expected and I can understand that. Can somebody explain above behaviour of this
?
private String test2Str;
private Test test = null;
public Test2(String str){
this.test2Str = str;
test = new Test(this);
}
Second Output of the program :
com.avnet.spoj.lifeuniverse.Test2@56e5b723
Hello World!
Hello World!