Here's my answer, which is pretty much like what @zposten provided, but also address's the OP's data[] array created at another function requirement:
public class EncapsulatedArray
{
private final int[] data;
public EncapsulatedArray(final int[] data)
{
this.data = data;
}
public int getPixel(final int i)
{
return data[i];
}
public void setPixel(final int i, final int x)
{
data[i] = x;
}
@Override
public String toString()
{
return Arrays.toString(data);
}
}
To verify and demonstrate, I used:
public class EncapsulatedArrayDemo
{
public static void main(final String[] args)
{
final int[] dataFromElsewhere = { 0, 1, 2, 3 };
final EncapsulatedArray ex = new EncapsulatedArray(dataFromElsewhere);
System.out.println(ex);
ex.setPixel(2, 7 + ex.getPixel(2));
System.out.println(ex);
}
}
and obtained the following to console:
{ 0, 1, 2, 3 }
{ 0, 1, 9, 3 }
There are various reasons why wrapper classes like this (toy) example are useful, but if you are hoping to "protect" the data array from outside changes (i.e. only setPixel(int, int) is allowed to modify values in data) then you'll need something more like @zposten's answer which never lets the data array object escape from the wrapper. If you do need to use a data array created at another function then something like my solution is required - but you'll have to take other steps to ensure that the array isn't fiddled with behind the wrapper's back.