How do I prevent the modification of a private field in a class?

前端 未结 10 1997
Happy的楠姐
Happy的楠姐 2020-12-22 16:45

Imagine that I have this class:

public class Test
{
  private String[] arr = new String[]{\"1\",\"2\"};    

  public String[] getArr() 
  {
    return arr;
         


        
10条回答
  •  余生分开走
    2020-12-22 17:21

    Modifier private protects only field itself from being accessed from other classes, but not the object references by this field. If you need to protect referenced object, just do not give it out. Change

    public String [] getArr ()
    {
        return arr;
    }
    

    to:

    public String [] getArr ()
    {
        return arr.clone ();
    }
    

    or to

    public int getArrLength ()
    {
        return arr.length;
    }
    
    public String getArrElementAt (int index)
    {
        return arr [index];
    }
    

提交回复
热议问题