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 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 whole array for the totalArray
method.
How can I prevent numArray
from being modified out of his class?
Encapsulation is the process of hiding the implementation. Whether the collection stores its data in an array or not is an implementation detail; if it was encapsulated you would want to be able to change it to another storage type.
Encapsulation can be achieved by Declaring all the variables in the class as private and writing public methods in the class to set and get the values of variables. It is more defined with the setter and getter method.
Encapsulation in Java is the process by which data (variables) and the code that acts upon them (methods) are integrated as a single unit. By encapsulating a class's variables, other classes cannot access them, and only the methods of the class can access them.
It is also possible to create arrays with two or more dimensions. Two dimensional arrays are useful for storing matrices for example. In Java, arrays of more than one dimension are created by making arrays of arrays. This is known as nesting.
All you can do to prevent people from changing your array is to provide a copy of it in the getter.
public int[] getArray() {
return Arrays.copyOf(numArray, numArray.length);
}
This way, other methods can change their own copy of the array, but when they call the getter again, they get the original version, unchanged. Only the setNumArray()
you provide can actually modify your internal array.
Otherwise, if you want to completely block the container, you have to drop arrays and use an immutable object. Some libraries provide immutable lists, or use Collections.unmodifiableList.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With