What is the Java equivalent of C++'s const member function?

后端 未结 9 615
长发绾君心
长发绾君心 2021-01-01 10:23

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

9条回答
  •  天涯浪人
    2021-01-01 10:55

    You could return a copy of the member, thus changes will not be reflected in the object the private reference points to. With primitives, of course, this problem doesn't exist.

    Be mindful of memory usage, however! This might not be the right solution for all situations. In that case, an immutable object as suggested in another answer might be the way to go.

提交回复
热议问题