Reputation: 491
This is for a personal project. Not assignment or work.
Say I have an object, objA
that has a function callB()
.
When I run callB()
it calls a function in object B. The function in objB
can have calls to functions in objA.
Eg. objA
calls callB()
.
Inside callB()
there is a function like setObjAName()
which sets a variable on objA
.
How would I do this in Java? How do I reference objA
from objB
?
Upvotes: 0
Views: 67
Reputation: 4125
The simplest method is to simply pass a reference to A in with the method call, which will allow for B to access any of A's public methods.
public class ClassA {
public String someAVar;
public void callB(ClassA a){
//do stuff
ClassB b = new ClassB();
b.setObjA(this,"newValue");
}
}
public class ClassB{
public void setObjA(ClassA A, String newValue){
A.someAVar = newValue;
}
}
Alternatively you might want the variable to be settable without passing in a particular instance, in which case static methods and variables are your friend.
public class ClassA {
public static String someAVar;
public void callB(){
//do stuff
ClassB b = new ClassB();
b.setObjA("newValue");
}
}
public class ClassB{
public void setObjA(String newValue){
ClassA.someAVar = newValue;
}
}
Upvotes: 1