The examples show that the submitter is confused; in the second example such a
method returns the value of the private field, not a reference to it
that could be used to modify the field externally. (Such a thing is
possible in C++ but not in Java; in Java, it is only possible to have
a reference to an object, not to an individual field or local variable.
For example, in Java the idiom for passing a reference to a variable as
an argument is to pass a single-element array that is explicitly dereferenced
similarly to the way pointers must be used explicitly in C.)
Note that as of 1.1 (with the inner classes specification) it is possible
to mark method parameters as "final", which is the most frequent use for
The evaluator above clearly didn't understand the submitter's request.
As other commentors have noted, in Java there are other idioms one can
use, such as the unmodifiable wrappers in the Collections classes.
These are sufficient (although certainly not as concise as C++).
Name: rm29839 Date: 11/18/97
One way to do this in Java is with subclassing. If you define a superclass
that has the read-only methods, then you can declare methods that take only that
superclass, and they won't be able to make any modifications to the instance.
You would still have to construct the fully-functional subclass, and there's
the extra overhead of reading (and writing) the superclass and the subclass.
Then if you wanted to do what in C++ was
*(AType*) &constInstance; /* cast away const-ness */
in Java you would narrow the instance to the subclass that has the modification
methods. (Of course, you could do the same thing in C++.)