public class foo {
private int a[];
private int b;
public foo(){
a = new int[] {1,2};
b= 3;
}
public int[] getA(){
return this.a;
}
public int getB(){
return this.b;
}
I noticed that it's possible to change a value of A by accessing the object like this:
foo f = new foo();
f.getA()[0] = 5; // f.a[0] changes to 5
but it isn't possible to do something like:
f.getB = 5; // gives error
f.getA() = new int[]{2,3}; //gives error
can someone explain me how this works, and how to prevent the user from changing the value of an array cell?
Thanks in advance.
In Java, array is a reference type, which means that the value of an array expression is a reference to the actual array.
The return value of getA()
is, therefore, a reference to the private array inside your object. This breaks encapsulation: you give access to your object's internals.
You can avoid this by either returning a reference to a copy of your internal array, or by providing a different API which only returns individual elements, say a method getA(int index)
.
f.get(A)
returns a reference to an array. You can access that array the way you access any array, and assign values to its elements with f.get(A)[i]=...
(though it makes more sense to store the returned array in a variable, which would let you access that array multiple times, without having to call f.get(A)
each time).
You can't, however, assign anything f.get(A)
via f.get(A)=..
, since a method call is not a valid left side of an assignment operator. For all you know, a call to f.get(A)
may generate a new array that is not referred to by a member of the foo
class, so assigning f.get(A)= new int[5];
would make no sense, since there would be no variable in which to store the new array.
The same explanation applies to f.getB() = 5;
.
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