I would like to share data between the objects.
Actually, for example, there is a World composed of Water and Individuals.
I would like the Individuals to access the Water.
I looked at transforming the Individual table in Collection, or making the Water a Singleton, but really, what would be the best design?
(we might have multi threading processes on the Individual object… So we might need a Thread safe implementation.)
(Also, I wonder about passing by argument or instantiate the Water for each Individuals, but it seems not to be the most efficient implementation (processing instantiation) ?…)
A simple set of objects in order to fix the ideas (this set does not share the Water at all, the Individuals display ‘null’ here) :
package myworld.testing;
public class World {
static Water evolution;
static Individual [] tribe;
public World(){
evolution=new Water();
}
public static Water getWater(){
return evolution;
}
public static void main(String[] args) {
evolution=new Water();
System.out.println("info "+evolution.get());
tribe = new Individual[10];
for(Individual individual : tribe){
System.out.println("trace "+individual);
}
evolution=new Water("sprakly");
System.out.println("info "+evolution.get());
for(Individual individual : tribe){
System.out.println("trace "+individual);
}
evolution.set("salty");
System.out.println("info "+evolution.get());
for(Individual individual : tribe){
System.out.println("trace "+individual);
}
}
}
package myworld.testing;
public class Individual {
int data;
public Individual(){
data=0;
}
public Individual(int i){
data=i;
}
public void set(int i){
data=i;
}
public int get(){
return data;
}
public String toString(){
return World.getWater().get()+" "+data;
}
}
package myworld.testing;
public class Water {
private static Water instance = null;
String type;
public static Water getInstance(){
if(instance == null) {
instance = new Water();
}
return instance;
}
public Water(){
type="1";
}
public Water(String str){
type=str;
}
public void set(String str){
type=str;
}
public String get(){
return type;
}
}
Thank you so much for your help and advice in advance.
Feel free to share your thoughts 🙂
The reason your getting
nullvalues while iterating over the array ofIndividuals is that, for each array element, you haven’t created an instance whose reference will occupy it. Instantiating an array merely creates a sequential memory block ofnullpointers. The correct solution is:In regards to your question about “individuals accessing the water,” you must declare the encapsulated instance of
WaterinWorldwith the public visibility modifier to grant access to all classes outside the package containingWorld.Given that
IndividualandWorldreside in the same package, using thepublicmodifier isn’t necessary.