As others have already pointed out: The array is passed as a reference to the Person
. So changes that are later done to the array will be visible to the Person
object. But that's only one half of the problem: You are not only passing a reference to the array to the constructor of the Person
, you are also returning a reference from the getArray
method.
Generally speaking, and as StephenC already pointed out in his answer: One important aspect of Object-Oriented design is to properly manage the state space of objects. It should not be possible for users of a class to bring an object into any form of "inconsistent state".
And this is difficult with plain primitive arrays. Consider the following pseudocode, referring to the class that you posted:
int originalArray[] = new int[2];
originalArray[0] = 12;
originalArray[1] = 34;
Person person = new Person(originalArray);
int arrayFromPerson[] = person.getArray();
originalArray[0] = -666; // Modify the original array
System.out.println(arrayFromPerson[0]) // Prints -666 - this is unexpected!
arrayFromPerson[1] = 12345678; // Modify the array from the person
System.out.println(originalArray[1]) // Prints 12345678 - this is unexpected!
Nobody knows who has a reference to the array, and nobody can verify or track that the contents of the array is not changed in any way. How critical this is becomes more obvious when you anticipate that the Person
object will be used at different places, possibly even by multiple threads.
Plain primitive arrays in Java do have their justification. But when they appear in the interface of a class (that is, in its public
methods), they should be view with scrutiny.
In order to be absolutely sure that nobody can interfere with the array that is stored in the Person
object, you'd have to create defensive copies everywhere:
public Person(int[] arrayTest) {
this.arrayTest = arrayTest.clone(); // Store a clone of the array
}
public int[] getArray() {
return this.arrayTest.clone(); // Return a clone of the array
}
But this may be cumbersome. A more object-oriented solution could be to expose a "read-only view" on the state that is represented with the array. For example:
public Person(int[] arrayTest) {
this.arrayTest = arrayTest.clone(); // Store a clone of the array
}
public int getArrayLength() {
return this.arrayTest.length;
}
public int getArrayElement(int index) {
return this.arrayTest[index];
}
(Of course, in practice, you'd name the methods accordingly, depending on what the array actually represents. For example, if it's the ages of the children of the person, you'd call the methods getNumChildren()
and getAgeOfChild(int i)
or so...)
Another option how this can be solved is to expose an (unmodifiable) List
view on the array. This can, for example, be done with the asUnmodifiableList
method that is shown in this answer.