How to make Date Immutable
posted 13 years ago
Date in java is mutable. Is there any way to make it Immutable other than creating an object with final key word.
Sheriff
posted 13 years ago
This would not make it immutable anyway. Its content would still be mutable.
You could make a wrapper class, but is is really necessary to go through all that pain ? Why do you want to make it immutable ?
posted 13 years ago
This would not make it immutable anyway. Its content would still be mutable.
You could make a wrapper class, but is is really necessary to go through all that pain ? Why do you want to make it immutable ?
Thanks for your reply. It is not my project requirement. Just thinking about how to implement this. Could you please help:
a) Why it would not be immutable if i use final while creating object of Date.
b) How to make wrapper class.
Java Cowboy
posted 13 years ago
Vijay jai Singh wrote: a) Why it would not be immutable if i use final while creating object of Date.
Because making a variable final only means that you cannot change the value of the variable itself; you can still change the state of the object that the variable refers to. For example:
Write a class yourself that has the same methods as class Date, except the set. () methods and other methods that might change the state. Put a private member variable of type Date in your class, and forward all calls to the Date object. For example:
Bartender
posted 13 years ago
Search the forums.
I remember reading an article on this in the Journal by Illja Preuss if I am not mistaken.
Bartender
posted 13 years ago
I was mistaken indeed. It was authored by David O’Meara. (I hope he is on vacation and doesn’t see this)
Sheriff
posted 13 years ago
posted 13 years ago
thanks Christophe, Jesper, Maneesh for your responses
posted 13 years ago
Vijay jai Singh wrote: a) Why it would not be immutable if i use final while creating object of Date.
Because making a variable final only means that you cannot change the value of the variable itself; you can still change the state of the object that the variable refers to. For example:
Write a class yourself that has the same methods as class Date, except the set. () methods and other methods that might change the state. Put a private member variable of type Date in your class, and forward all calls to the Date object. For example:
i feel when the state of the object change there should be new object for the immutable object so wht code which you mentioned i think will not give immutable object when there is situvation like
data+20 days should be new date object so we need to extend the date class and use super to call the parent instance and the result need to be returned as new date object(i have seen that same thing implemented in string class in java).