I created an instance of a class in java as following:
ABC ab = new ABC();
I want to access this instant ab in another class
There are several ways to do what you want to achieve. Some of them might be as follows:
Passing the object reference through a constructor
Here, you would explicitly pass the reference of your reference class when you're creating an object of the actual class.
public class ActualClass{
private ReferenceClass refClassObject;
/**
* Passing through a constructor
*/
public ReferenceClass(ReferenceClass refClassObject){
this.refClassObject = refClassObject;
}
}
class ReferenceClass{
/**
* Your implementation of the class
*/
}
Using getter/setter methods
In this approach, you would pass the reference of your object through explict public setXX() methods. This approach is more flexible because you can update the reference object as and when you want to (think polymorphism). As an example:
public class ActualClass{
private ReferenceClass refClassObject;
public ActualClass(){
}
public void setReferenceClass(ReferenceClass refClassObject){
this.refClassObject = refClassObject;
}
public ReferenceClass getReferenceClass(){
return refClassObject;
}
}
class ReferenceClass{
/**
* Your implementation of the class
*/
}
Using a combination of constructors and getters/setters
For added flexibility, you might want to initialize your Actual class object with a reference. However if you would also want to keep the option of changing the reference at object at a later stage, go for a combination of both #1 & #2 that I specified above.
public class ActualClass{
private ReferenceClass refClassObject;
public ActualClass(){
}
public ActualClass(ReferenceClass refClassObject){
this.refClassObject = refClassObject;
}
public void setReferenceClass(ReferenceClass refClassObject){
this.refClassObject = refClassObject;
}
public ReferenceClass getReferenceClass(){
return refClassObject;
}
}
class ReferenceClass{
/**
* Your implementation of the class
*/
}
Which one should you choose? Well it would depend on your implementation and requirement.