There are many immutable classes like
String, Boolean, Byte, Short, Integer, Long, Float, Double etc. In short, all
the wrapper classes and String class is immutable. We can also create immutable
class by creating final class that have final data members as the example given
below
Steps to create
immutable class:
1. The instance variable of the class is final i.e. we cannot change the value
of it after creating an object.
2. The class is final so we cannot create the subclass.
3. There is no setter methods i.e. we have no option to change the value of the
instance variable.
4. In the constructor we use the import org.joda.time.DateTime class. This is a
better version than the java.util.Date because it is immutable. Using a
java.util.Date would be dangerous as it is a mutable class and we can't control
the calling thread (which might modify it).
Example:
No comments:
Post a Comment