Search code examples
javaobjectreferenceencapsulationgetter

Trick the private keyword in Java


I am aware that the idea of the keyword private is to enable encapsulation. However, I got confused when I realized that I can modify an Array after retrieving it with a getter, which surprised me. The same didn't work for the plain integer, although I thought java treats all variables as objects.

The example:

public class PrivContainer {
private int[] myIntArray;
private int myInt;

PrivContainer(){
    myIntArray=new int[1];
    myIntArray[0]=3;
    myInt=22;
}

public int[] getIntArray(){
    return myIntArray;
}

public int getInt(){
    return myInt;
}

public void printInt(){
    System.out.println(myIntArray[0]);
    System.out.println(myInt);
}
}


public class Main {
public static void main(String[] args){
    PrivContainer pc=new PrivContainer();
    int[] r=pc.getIntArray();
    int q=pc.getInt();
    r[0]=5;
    q=33;
    pc.printInt();
}
}

The Output of printInt() is 5,22

This means that main method could change the entries of the private array but not of the private int.

Could someone explain this phenomena to me?


Solution

  • An array is a mutable Object. Therefore, if you have a reference to that array, you can modify its contents. You can't do the same with primitive members of a class (such as int) and with references to immutable class instances (such as String and Integer).

    Your assignment :

    q=33;
    

    Would be similar to :

    r = new int [5];
    

    Both of those assignments cause the variables to contain new values, but they don't affect the state of the PrivContainer instance from which the original values of those variables were assigned.