Skip to main content

JSR Proposal - immutable class modifier

Please note these forums are being decommissioned and use the new and improved forums at
1 reply [Last post]
Joined: 2007-06-01

I would like to propose a change to the Java Language Specification (JLS), to include a new class modifier:
<strong><code>immutable</code></strong>. This modifier would be used in situations where an immutable object
is needed to maintain data integrity, with ease of code maintenance.

The idea is that the compiler would check that all instance variables of the implementing class, and its subclasses,
have been set to: <code>final</code>. That is all. By doing this, it prevents the data being potentially corrupted. In addition,
a more complex implementation of this specification, could allow the compiler to 'imply' all instance variables are
'final' when they are not 'explicitly' set as such. This would help in modifying legacy code, by simply allowing the
addition of the <code>immutable</code> modifier to a class' definition.

The same can be achieved by due diligence on the part of programmers, by themselves making sure that all the instance
variables are set as <code>final</code>, but this can be a problem later on, during the maintenance phase. To assist myself in this,
I have created a 'tag interface' :, which is an empty interface. This helps me to remember that this
class' instance variables MUST be kept as <code>final</code>. However, I am only human, and therefore subject to mistakes, such as,
forgetting to set an instance variable of a subclass of a class that implements 'Immutable', as <code>final</code>. Thus breaking
the 'immutable' contract/state of the class. This becomes even more of a problem, when dealing with third party libraries, where
it is desirable for a class to be both <code>immutable</code> and not <code>final</code>. Thereby allowing the sub-classing of
<code>immutable</code> classes to occur.

* This class is immutable
* @author Brad Willcott
public class immutable AnImmutableClass {

/** Height of object */
public final int height;

/** Length of object */
public final int length;

/** Width of object */
public final int width;

* Constructs a new AnImmutableClass object.
* @param height of object
* @param width of object
* @param length of object
public AnImmutableClass(final int height, final int width, final int length) {
this.height = height;
this.length = length;
this.width = width;

<em><strong>Note:</strong> The <code>final</code> modifiers used on the parameters of the constructor are NOT
a requirement of this specification, but simply a recommendation only.</em>

Reply viewing options

Select your preferred way to display the comments and click "Save settings" to activate your changes.
Joined: 2007-06-01

I have moved this to a new discussion group:

All interested parties are welcome.