I'm starting with Java and I'm learning about setters, getters and encapsulation. I have a very simple program, two classes:
Container
has a private int array (numArray
) with his setter & getter.Main
creates aContainer
object and uses it intotalArray
method.
public class Container {
private int numArray[]= {0,0,0};
public int[] getNumArray() {
return numArray;
}
public void setNumArray(int index, int value){
numArray[index] = value;
}
}
public class Main {
public static void main(String[] args) {
Container conte = new Container();
System.out.println(totalArray(conte.getNumArray()));
conte.getNumArray()[2]++;
System.out.println(totalArray(conte.getNumArray()));
}
private static int totalArray (int v[]){
int total=0;
for (int conta =0; conta<v.length;conta++){
total+=v[conta];
}
return total;
}
}
Problem: I can change the private int array through the getter, I know that's because getNumArray
returns a reference to numArray
, not the array itself. If I were interested in a single element of the array, I'd make a getter with an index value, but I want the whole array for the totalArray
method.
How can I prevent numArray
from being modified out of his class?