Java: What modifier makes the object readable outside the class, but not writable? And the object can be changed within the class.
Asked
Active
Viewed 341 times
-6
-
5Make a private setter and public getter – that other guy Dec 19 '17 at 22:54
-
@thatotherguy That's not a modifier – Titan Dec 19 '17 at 23:01
-
2There's no such modifier. Do what Zamrony suggests. – Dawood ibn Kareem Dec 19 '17 at 23:06
-
@DawoodibnKareem Well that's disappointing. – Titan Dec 19 '17 at 23:09
2 Answers
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
-
-
AFAIK, there are only `private`, `protected` and `public` for scope modifiers in Java – Zamrony P. Juhara Dec 19 '17 at 23:08
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