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

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

    I don't think there is a way to that in Java for non primitive objects (you're always passing around references to such objects). The closest you could do would be to return a copy of the object (using clone or something like that) ; but that would not be very idiomatic Java.

    I you want to give access only to the 'visible' part of a member object, what you could do is create an interface with the visible part, and return this interface. For example :

    public interface Bar {
         public int getBing();
    }
    
    public class BarImpl implements Bar {
         private int bing;
         public int getBing() {
            return bing;
         }
         public void setBing(int bing) {
            this.bing = bing;
         }
    }
    
    public class Foo {
         private BarImpl bar;
    
         public Bar getNonModifiableBar() {
             return bar; // Caller won't be able to change the bing value, only read it.
         }
    }
    

提交回复
热议问题