Is there a way to prevent the private field of the class from being modified?

Asked 2 years ago, Updated 2 years ago, 90 views

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

2022-09-21 22:17

1 Answers

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.


2022-09-21 22:17

If you have any answers or tips

Popular Tags
python x 4647
android x 1593
java x 1494
javascript x 1427
c x 927
c++ x 878
ruby-on-rails x 696
php x 692
python3 x 685
html x 656

© 2024 OneMinuteCode. All rights reserved.