Browse DevX
Sign up for e-mail newsletters from DevX

Tip of the Day
Language: Java Language
Expertise: Beginner
Apr 5, 1999



Building the Right Environment to Support AI, Machine Learning and Deep Learning

Read-only members

If I write a class in C++, which contains private members, I can make them read-only by providing a get access method and no set access method. If that member is large and I want to return it by reference, I can maintain security by returning a const reference. Without being able to do this, what does a Java programmer do to make read-only member objects, accessed (as they must be) by reference?

Const references in C++ can be compromised by casting and throwing away the const attribute. So the problem you are trying to solve for Java also needs to be solved for C++. A solution that will work in both languages is to tackle the problem through design rather than language features. Think carefully about why you want to grant access to a private member variable. If you are designing a class library and other classes need to read the value of the variable, then it is better to make the variable package local if you are concerned about providing efficient access to the value. Within the package, you can enforce read-only access by ensuring that all external class accesses within the package do not modify the value of the variable. The safest solution is probably not to return a reference to the variable in a get method in either Java or C++. Rather, you should copy the value of the variable to a new variable. A shallow copy may be sufficient for some data structures, but remember to make deep copies when necessary. Finally, if the variable is truly to be read-only in all situations, it should be declared final and initialized a single time.

DevX Pro
Comment and Contribute






(Maximum characters: 1200). You have 1200 characters left.



Thanks for your registration, follow us on our social networks to keep up-to-date