-6

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

Titan
  • 33
  • 10

2 Answers2

2

To make public read-only field, you can make field private and a public getter for this field.

public class Example {
       private  int myExample=1;
       public int getMyExample() {
              return myExample;
       }
}
Zamrony P. Juhara
  • 5,222
  • 2
  • 24
  • 40
1

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.

John Bollinger
  • 160,171
  • 8
  • 81
  • 157