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

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

    There's no equivalent to the C const "type modifier" in Java (sadly).

    The closest you can get is to return an immutable object or an immutable wrapper around a mutable object.

    Immutability is not a language feature of Java, however, so you'll have to rely on Libraries.

    Examples of immutable objects are:

    • the primitive wrappers Integer, Character, ..
    • String
    • File
    • URL

    Commonly used immutable wrapper (i.e. wrappers around mutable types that prevent mutation) are those returned by the Collecton.unmodifiable*() methods.

提交回复
热议问题