This is a bit of an old question, but I thought I would contribute my 2 cents anyway since this thread came up in conversation today.
This doesn't exactly answer why is there no const? but how to make your classes immutable. (Unfortunately I have not enough reputation yet to post as a comment to the accepted answer)
The way to guarantee immutability on an object is to design your classes more carefully to be immutable. This requires a bit more care than a mutable class.
This goes back to Josh Bloch's Effective Java Item 15 - Minimize Mutability. If you haven't read the book, pick up a copy and read it over a few times I guarantee it will up your figurative "java game".
In item 15 Bloch suggest that you should limit the mutability of classes to ensure the object's state.
To quote the book directly:
An immutable class is simply a class whose instances cannot be modified. All of the information contained in each instance is provided when it is created and is fixed for the lifetime of the object. The Java platform libraries contain many immutable classes, including String, the boxed primitive classes, and BigInte- ger and BigDecimal. There are many good reasons for this: Immutable classes are easier to design, implement, and use than mutable classes. They are less prone to error and are more secure.
Bloch then describes how to make your classes immutable, by following 5 simple rules:
- Don’t provide any methods that modify the object’s state (i.e., setters, aka mutators)
- Ensure that the class can’t be extended (this means declaring the class itself as
final
).
- Make all fields
final
.
- Make all fields
private
.
- Ensure exclusive access to any mutable components. (by making defensive copies of the objects)
For more details I highly recommend picking up a copy of the book.
const
keyword, but there is no underlying feature. Corrected your title and tags accordingly. – Vivyan