Reputation: 35
I am confused with the memory allocation of references in Java when you pass them to the methods in Java. As a Test I did an example as below,
class Store{
public int[] buffer = new int[5];
}
class ConsumeStore{
Store store;
public ConsumeStore(Store store){
this.store = store;
}
public int useStore(){
return store.buffer[0];
}
}
class ProduceStore{
Store store;
public ProduceStore(Store store){
this.store = store;
}
public void putStore(){
store.buffer[0] = 100;
}
}
public class CheckRef {
public static void main(String args[]){
Store store = new Store();
ConsumeStore consStore = new ConsumeStore(store);
ProduceStore prodStore = new ProduceStore(store);
prodStore.putStore();
System.out.println(consStore.useStore());
}
}
Well the output is 100.
Here I am passing the Store reference to ProducerStore. Inside ProducerStore I am assigning it to the class member of it. I am doing the same for ConsumerStore as well.
Could someone explain me how the memory allocation is done for Store referece and how it shared among the ProducerStore and ConsumerStore?
Upvotes: 0
Views: 81
Reputation: 19185
You need two separate instances.If you pass the same reference then any change will get reflected on both objects since they are pointing to same reference.
Store store = new Store();
ConsumeStore consStore = new ConsumeStore(store);
Store anotherStore = new Store();
ProduceStore prodStore = new ProduceStore(anotherStore);
Few notes
You should read Lesson: Object-Oriented Programming Concepts
Upvotes: 1
Reputation: 22812
Both your ProducerStore
and ConsumerStore
have a reference to the same object store
, that you passed to each one.
So when you modify store
internal state (its buffer
member), either externally or in any of the Producer/Consumer, all the classes that have reference to it are "updated" because they don't hold a distinct value, they only hold a reference to the unique value store
.
Something different would happen if you reallocated the object entirely. For example:
public void putStore(){
store = new Store()
store.buffer[0] = 100
}
In this case, the Consumer and the Producer would have a different store: Consumer would still have a reference to the original store, while Producer would have the new one defined within the Put method.
You can think of it as: everytime you do a new
, a new object is created in memory. Then when you pass it around to classes, everyone only has reference to that unique object.
Upvotes: 3