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

后端 未结 9 612
长发绾君心
长发绾君心 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 11:10

    You haven't overlooked anything. There is no way in pure Java to do so. There might be libraries which provide some subset of this using annotations, but I don't know any offhand.

    The way you pass back a reference to immutable data is to make the class you pass back immutable, plain and simple. There are a couple of library functions to help you produce an immutable view of some data in some very limited but common cases. Here's one example:

    private List internalData;
    
    public List getSomeList() {
        return Collections.unmodifiableList(internalData);
    }
    

提交回复
热议问题