Search code examples
javaaccess-modifiersmodifier

Java: What modifier makes the object readable outside the class, but not writable?


Java: What modifier makes the object readable outside the class, but not writable? And the object can be changed within the class.


Solution

  • For a field to be modifiable by its class's methods, it must be non-final. There is no modifier or combination of modifiers that grants read access to such a field without granting write access as well. Access-control modifiers (public, protected, private, or the absence of any of those) control the visibility of a field or method for all purposes at once. They do not discriminate between different types of access.

    If you want a modifiable field to be readable but not writable, then the only alternative is to protect it behind a getter method, without providing a corresponding setter, as another answer already describes.