How to access object in another class. | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 1

How to access object in another class.

If i declared any object in class A and i want to access it from class B.How can i access the object?

10th May 2018, 5:52 PM
Faisal Rahman
Faisal Rahman - avatar
2 Answers
+ 1
If I take your question literally you have a method (the access modifier doesn’t really matter) and you want to access a method on another object: private void myMethod () { otherObject.otherMethod ();} Obviously, in order to do so you’ll have to pass that object into your class. There is several options depending on your actual case: Pass the object instance in your classes’ constructor. This means you’ll manage both the object’s and your class instance’s lifecycle from outside. From the main class for example. OtherObject.java public class OtherObject { public void otherMethod () { }}  MyClass.javapublic class MyClass { private OtherObject otherObject;  public MyClass(OtherObject otherObject) { if (otherObject == null) throw new IllegalArgumentException(); this.otherObject = otherObject; }  public void myMethod () { otherObject.otherMethod (); }}  Main.java public class Main { public static void main(String[] args) { OtherObject oo = new OtherObject(); MyClass myClass = new MyClass (oo); myClass.myMethod (); }} If the other object’s lifecycle can be managed from your calling class, instantiate it in your calling class: MyClass.java public class MyClass { private OtherObject otherObject;  public MyClass() { this.otherObject = new OtherObject (); }  public void myMethod () { otherObject.otherMethod(); }} If the other object is not Thread Safe you must create a new instance before you use it. That is, if your app is multithreaded. public void myMethod () { OtherObject oo = new OtherObject(); oo.otherMethod(); } Funny enough I first read your question as ‘how can I access a private method on another class
10th May 2018, 6:01 PM
MsJ
MsJ - avatar
0
To be able to declare a class A object in class B, first you need to "import" class A into class B and then you can declare and instantiate a class A object in class B, and any method in class A will be available to you in class B through the class A instantiated object in class B. This is how it is. Please consider that the Garbage Collector release the memory of all objects not in use anymore. Good luck Faisal.
10th May 2018, 6:07 PM
Roberto Guisarre
Roberto Guisarre - avatar