+ 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?
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
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.