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

后端 未结 9 546
长发绾君心
长发绾君心 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:56

    When you do something like this:

    Object2 obj2 = obj1.getObj2();
    obj2 = new Object2();
    

    The original private member (obj1.obj2) remains as it were before (just to be sure that you grasped that concept). You can just omit the setter to obj2 so that the inner field cannot de changed.

    If you want Object2 fields to be immutable you will need to apply the same pattern (private fields, no setters).

    This answer your question?

提交回复
热议问题