I was wondering (there has to be an easy solution) if there is a way to make a number of objects, and use them in other classes and objects from those classes, without having to update them (in Java). An example:
Class A, B and C make objects a b and c.
Then I have class D, which makes object d.
Now I want to use d in a, change it, use d in b, change it there and use d in c and still have all the changes from a and b.
I know it’s possible with using d as an argument in the functions, and returning d, but that is not useful in the program I’m making at the moment.
Any help?
Ok, My example in code:
public class A {
D d = new D ();
A(D dObject){
this.d = dObject;
}
public void add () {
DObject.add(5);
}
}
public class B {
D d = new D ();
B(D dObject){
this.d = dObject;
}
public void add () {
DObject.add(5);
}
}
public class C {
D d = new D ();
C(D dObject){
this.d = dObject;
}
public void add () {
DObject.add(5);
}
}
public class D {
public int x=0;
public void add (int y){
x +=y;
}
}
// in main class:
D d = new D();
A a = new A(d);
B b = new B(d);
C c = new C(d);
a.add();
b.add();
c.add();
// d.x should give 15 now.
I’m not sure if I understand right – the code you posted does exactly what you say (
d.xis 15), if you correct the syntax errors.Here is a version that should work:
If you want
dto stay the same instead of changing (e.g.d.x == 0at the end), you can do one of these:dObjectin the constructor of A, B, C, so each has its ownDobject.Dimmutable and let itsaddmethod instead return a newDobject. Theaddmethod ofA,B,Cwould then have the implementationd = d.add(5);.