0

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.

0

3 Answers 3

2

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();
    }
}
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you so much for this. I tried printing out the hashes, and now I know that my program is somehow changing the objects between the method calls. Now I just have to figure out where (:
2

Yes.

Java will not change objects behind your back.

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.