I'm creating a custom array class, and it has an int
property size
.
This property is modified automatically if you do something like add()
or remove()
. I want to let the user read this property like myArray.size
. However, making it public
allows the user to change it, which doesn't make much sense for my class, and could break it.
I could of course make it private
and create a getter method size()
and all's good. I don't have a problem with that, but still, is there a way to make a read-only property in Java?
Looking around the web, I found this:
Their solution goes like
public final String title;
Which is tecnically valid, but that of course doesn't work for my array, since my property is not constant.
In Java, you can use Collections. unModifiableList() method to create read-only List, Collections. unmodifiableSet() for creating read-only Set like read-only HashSet and similarly creating a read-only Map in Java, as shown in below example. Any modification in the read-only List will result in java.
Java final variables are also not implicitly static. You can declare a read-only variable as static (e.g. static readonly int j; ), and initialize it either: - on the same statement as the declaration; or.
To make the file read-only, setReadOnly() method of File Class is used. This method returns the boolean value, which is used to check whether the task(to make the file read-only) got successful or not. If the value returned by the method is true, it means that the task was successful and vice versa.
We can make a class write-only by making all of the data members private. Please note: If we made a class write-only then we can modify the properties or data member value of the class. If we made a class write-only then we can only write the properties or data members value of the class.
What you're describing is not possible in Java.
I think what you want is for the user to be able to get the object's size but not be able to write to it. In this case, you keep the value of size
as private
. You are absolutely right that making size public
will allow a user to break your objects by setting the value of size
to something that it is not!
What you want is a getSize()
method that is public
and return
' s the value of size
. The user can call the method to read the value, but has no way of actually writing to the value of size
.
If you really want to learn about making part or all of your data structure immutable, you could check here:
Immutable Objects http://docs.oracle.com/javase/tutorial/essential/concurrency/immutable.html
Make use of getters/setters. Or rather, just getters without the setters in your case.
Look for an example here: http://docs.oracle.com/javaee/6/tutorial/doc/gjbbp.html
So make the property private, and create a public method to 'get' its value.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With