且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

什么是C ++的const成员函数的Java等价物?

更新时间:2022-10-15 08:48:38

您要么返回不可变的对象,或返回私有实例变量的副本。这样,对象的内部状态被保护免于修改,即:

  private MyMutableObject mutable = ... 

public MyMutableObject getMutableObject(){
返回new MyMutableObject(this.mutable);
}
`


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 data member in any way.

Is there a way to do this in Java?

If so, how?

I know about the final keyword but AFAIK, when applied to a method it:

  1. Prevents overriding/polymorphing that method in a subclass.
  2. Makes that method inline-able. (see comment by @Joachim Sauer below)

But it doesn't restrict the method from returning a reference to a data member so that it can't modified by the caller.

Have I overlooked something obvious?

You either return an immutable object, or return a copy of the private instance variable. This way, the object's internal state is "protected" from modification, i.e.:

private MyMutableObject mutable = ...

public MyMutableObject getMutableObject() {
   return new MyMutableObject(this.mutable);
}
`