So this may be a very simple question that I’m overthinking but if I do something like the following:
class A{
public String test_string = "before (default)";
public A(){
B b = new B(this);
}
public void testA(){
this.test_string = "after (new)";
}
}
where B is:
class B{
private A parent;
public B(A mParent){
parent = mParent;
}
private void testB(){
System.out.println(parent.test_string);
}
}
Would that allow me to still access the same instance of A (all of its public fields and methods)? If I called A.testA() from another class somewhere else on that specific instance of A, would the B that was constructed in that A‘s constructor’s testB function return the "after (new)" string? Or would that be a copy of A because doesn’t java assign by value, not reference? Is there a better way of doing this? Am I just over complicating the issue?
I wasn’t sure what to search for so I couldn’t find other questions that answered my question.
Thanks in advance!
Yes, it is the same instance. It works like shown in this image:
So, calling a method over b.parent.foo, it is called over the same instance passed in the constructor.