What is immutable class? how to make a Class explicitly
"Immutable"?Wap to make a class explicitly immutable.
Answer Posted / qamrun nisa
Immutable objects whose state (i.e. the object’s data) does
not change once it is instantiated (i.e. it becomes a
read-only object after instantiation). Immutable classes are
ideal for representing numbers (e.g. java.lang.Integer,
java.lang.Float, java.lang.BigDecimal etc are immutable
objects), enumerated types, colors (e.g. java.awt.Color is
an immutable object), short lived objects like events,
messages etc.
Writing an immutable class is generally easy but there can
be some tricky situations. Follow the following guidelines:
1. A class is declared final (i.e. final classes cannot be
extended).
public final class MyImmutable { … }
2. All its fields are final (final fields cannot be mutated
once assigned).
private final int[] myArray; //do not declare as -> private
final int[] myArray = null;
3. Do not provide any methods that can change the state of
the immutable object in any way – not just setXXX
methods, but any methods which can change the state.
4. The “this” reference is not allowed to escape during
construction from the immutable class and the immutable
class should have exclusive access to fields that contain
references to mutable objects like arrays, collections
and mutable classes like Date etc by:
• Declaring the mutable references as private.
• Not returning or exposing the mutable references to the
caller (this can be done by defensive copying)
| Is This Answer Correct ? | 1 Yes | 0 No |
Post New Answer View All Answers
What’s meant by anonymous class?
What are the restriction imposed on a static method or a static block of code?
What is finalize()? Is finalize() similar to a destructor?
What is the difference between menuitem and checkboxmenu item?
What is an example of character?
Explain methods specific to list interface?
Can we have a method name same as class name in java?
What is the default value of an object reference declared as an instance variable?
What are measurable parameters?
What are the differences between path and classpath variables?
What are the different types of inheritance in java?
Can we declare a class as static?
Is static variable stored in heap?
Is array serializable java?
What is string example?