In C++, I can define an accessor member function that returns the value of (or reference to) a private data member, such that the caller cannot modify that private
I don't think there is a way to that in Java for non primitive objects (you're always passing around references to such objects). The closest you could do would be to return a copy of the object (using clone or something like that) ; but that would not be very idiomatic Java.
I you want to give access only to the 'visible' part of a member object, what you could do is create an interface with the visible part, and return this interface. For example :
public interface Bar {
public int getBing();
}
public class BarImpl implements Bar {
private int bing;
public int getBing() {
return bing;
}
public void setBing(int bing) {
this.bing = bing;
}
}
public class Foo {
private BarImpl bar;
public Bar getNonModifiableBar() {
return bar; // Caller won't be able to change the bing value, only read it.
}
}