Saturn
Saturn

Reputation: 18139

Can I create read-only properties in Java?

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.

Upvotes: 9

Views: 18881

Answers (5)

Brandon
Brandon

Reputation: 1605

What you're describing is not possible in Java.

Upvotes: 7

Philipp Claßen
Philipp Claßen

Reputation: 43960

A simple getter is the natural approach, as Java lacks support for properties. So, a getter is what the typical Java programmer would expect.

Even if it is possible to use public fields, as in your public final String title example, I would not recommend it. For example, it is annoying when you give your code to someone else who wants to write unit tests for it and uses mocking frameworks.

Public fields should generally be reserved for (static) constants.

Upvotes: 0

Saher Ahwal
Saher Ahwal

Reputation: 9237

If you want to make a read only array, you can use ImmutableList : http://docs.oracle.com/cd/E15523_01/apirefs.1111/e13403/oracle/javatools/util/ImmutableList.html

Upvotes: 0

user1445967
user1445967

Reputation: 1570

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

Upvotes: 4

nl-x
nl-x

Reputation: 11832

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.

Upvotes: 2

Related Questions