Reputation: 115
Consider the scenario below:
public class ClassA {
private Main main;
Object obj = new Object;
public void setMain(Main main) {
this.main = main;
}
methodA() { //called first
obj.someFunction();
main.someFunction();
}
methodB() { //called second
obj.someOtherFunction();
}
}
Would methodB be using the same instance of "obj" as methodA? If not, how could the code be altered to make it so?
I apologize for such a basic question, but it is a concept that has been unclear for me since I started learning java, even after countless searches online.
Upvotes: 0
Views: 46
Reputation: 63167
If you're test case is:
ClassA objectA = new ClassA(new Main());
objectA.methodA();
objectA.methodB();
with nothing in between the calls to methodA()
then methodB()
that would change the value of the obj
instance variable, then yes, they would both use the same obj
instance.
Upvotes: 0
Reputation: 7100
Yes.
If you want to visualize that, you can just print the object to see that hash:
public class ClassA {
private Main main;
Object obj = new Object;
public void setMain(Main main) {
this.main = main;
}
methodA() { //called first
System.out.println(obj); //you should see the same hash as in methodB
obj.someFunction();
main.someFunction();
}
methodB() { //called second
System.out.println(obj); //you should see the same hash as in methodA
obj.someOtherFunction();
}
}
Upvotes: 3