Question: Hello, I am trying to use the same Object between two different methods but I am having trouble in Java. The methods are being called

Hello, I am trying to use the same Object between two different methods but I am having trouble in Java. The methods are being called but it is by different object. How can I pass the same object to retain the same data. Here is my code. When I print out the objects its listed as ObjA@33909752 for one and ObjA@55f96302 for another. I want them both to be the same like (ObjA@33909752 and ObjA@33909752).

Thanks

import java.io.IOException;

public class Main {

public static void main(String[] args) throws IOException {

// TODO Auto-generated method stub

ObjA obj = new ObjA();

passObj2(obj );

passResult(obj);

}

private static ObjA passResult(ObjA o) throws IOException {

// TODO Auto-generated method stub

ObjA obj1 = new ObjA();

obj1.setObjA();

System.out.print(obj1);

obj1=o;

return o;

}

private static void passObj2(ObjA o) throws IOException {

// TODO Auto-generated method stub

System.out.print(o);

o.setObjB();

}

}

- - - - - - - - - - -

import java.io.IOException;

public class ObjA {

public void setObjA() throws IOException{

int A = 1;

}

public void setObjB() throws IOException{

int B = 1;

}

}

Step by Step Solution

There are 3 Steps involved in it

1 Expert Approved Answer
Step: 1 Unlock blur-text-image
Question Has Been Solved by an Expert!

Get step-by-step solutions from verified subject matter experts

Step: 2 Unlock
Step: 3 Unlock

Students Have Also Explored These Related Databases Questions!