Hi, i'm starting with Java and i'm learning about setters,getters and encapsulation.
I have a very simple program, 2 classes:
Container has a private int array (numArray) with his setter & getter.
Main creates a Container object and uses it in totalArray 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 hole array for the totalArray method.
How can i prevent numArray from being modified out of his class?
Sorry for my poor English ^^. Thx