Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

java

readonly

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?

like image 402
Pacerier Avatar asked Nov 16 '11 12:11

Pacerier


People also ask

Does Java have readonly?

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.

What is readonly class in Java?

Defining read-only class in Java If we make a class read-only, then we can't modify the properties or data members value of the class. If we make a class read-only, then we can only read the properties or data members value of the class.

When should you use a read-only field?

In a field declaration, readonly indicates that assignment to the field can only occur as part of the declaration or in a constructor in the same class. A readonly field can be assigned and reassigned multiple times within the field declaration and constructor.

What is the purpose of a field in Java?

A Java field is a variable inside a class. For instance, in a class representing an employee, the Employee class might contain the following fields: name. position.


1 Answers

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);     } } 
like image 54
Aleks N. Avatar answered Sep 18 '22 10:09

Aleks N.