In java array carries reference to a memory location and objects does that too. So when we create an array of objects, does that mean that the array carries reference to more references?
I asked this question to my professor, but didn't quite understand what he explained.
CodePudding user response:
When you write:
Object[] array = new Object[10];
the variable array
contains a reference. This reference points to an array object, which can contain 10 references. These references are all null
at the point that the array is created.
Once you write:
array[0] = new Object();
array[0]
now contains a reference to an Object
instance.
CodePudding user response:
Yes.
Suppose you have code like this:
class Foo { ...
public int getBar () { ...
public void setBar (int bat) { ...
Now, elsewhere you have code like this:
Foo [] glorblarr = new Foo [12];
Foo flarg = new Foo ();
...
flarg.setBar (100);
glorblarr [7] = flarg;
System.out.println (flarg.getBar () " " glorblarr [7].getBar ());
glorblar [7].setBar (987);
System.out.println (flarg.getBar () " " glorBlarr [7].getBar ());
You should expect the output to be this:
100 100
987 987
At this point, globarr [7]
refers to the same Object as flarg
. That is, one Object, but it is accessible via two names / references. At least until one of the references is changed to point to something else (or null
), one is an alias for the other.