Do we have a Readonly field in java (which is set-able within the scope of the class itself)?

Pacerier picture Pacerier · Nov 16, 2011 · Viewed 59.9k times · Source

How can we have a variable that is writable within the class but only "readable" outside it?

For example, instead of having to do this:

Class C {
  private int width, height;

  int GetWidth(){
    return width;
  }

  int GetHeight(){
    return height;
  }

  // etc..

I would like to do something like this:

Class C {
  public_readonly int width, height;

  // etc...

What's the best solution?

Answer

Aleks N. picture Aleks N. · Feb 20, 2014

Create a class with public final fields. Provide constructor where those fields would be initialized. This way your class will be immutable, but you won't have an overhead on accessing the values from the outside. For example:

public class ShortCalendar
{
    public final int year, month, day;

    public ShortCalendar(Calendar calendar)
    {
        if (null == calendar)
            throw new IllegalArgumentException();

        year = calendar.get(Calendar.YEAR);
        month = calendar.get(Calendar.MONTH);
        day = calendar.get(Calendar.DATE);
    }
}