How does returning by enable access control? (Java)

In Java, when you make a getter for a private field of class as follows(assume child is an ArrayList):

public ArrayList getChild() {
    return this.child;
}

you return a reference to the private field "name" (which means the ArrayList can be modified using that reference??) In C++, this same kind of code would return a copy, which would leave the object's field unharmed if that copy were manipulated.

Can you modify the private member by calling this method and then modifying the returned ArrayList reference? If yes, how does having a getter in a language like Java control access, then? And what is the proper way to write a getter that will protect the private members?

Jon Skeet
people
quotationmark

you return a reference to the private field "name"

Well, not quite. You return the current value of the child field. It's important to understand that that's not the same as somehow returning a reference to the field itself. After the method has returned, any changes to the field (e.g. setting it to null, or making it refer to a different list) will not be seen by the method caller. It's important to differentiate between the field, the reference (which is the value of the field) and the object that the reference refers to.

How does having a getter in a language like Java control access, then?

It doesn't, directly.

And what is the proper way to write a getter that will return a copy?

That depends on the type. If you use immutable types, you don't need to copy anyway :)

For collections, you could potentially create a read-only view over the original collection - but then the caller will still see changes to the original collection. Or you can just explicitly create your own copy, e.g.

return new ArrayList<>(child);

people

See more on this question at Stackoverflow