public class Test
{
private String[] arr = new String[]{"1","2"};
public String[] getArr()
{
return arr;
}
}
When there's a code like this
Test test = new Test();
test.getArr()[0] ="some value!"; //!!!
Then the problem here is that you access the private field from outside. How do I stop this? I mean, I want to prevent the value of this array from changing, but the getter method somehow makes the private field accessible. How shall I do it?
class oop java array
You can return a copy of the array from the getter method.
public String[] getArr() {
return arr == null ? null : Arrays.copyOf(arr, arr.length);
}
Like this.
© 2024 OneMinuteCode. All rights reserved.