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


Please Help Members By Posting Answers For Below Questions

what is function overloading in java?

697


What is the purpose of static methods and variables?

533


Why java applets are more useful for intranets as compared to internet?

580


What is difference between equals and hashcode method?

572


Is 0 true or is 1 true?

518






Who found java?

553


What are the two ways to create a thread?

536


What design pattern you have used in your project? I answered Factory pattern, how it is implemented? What are its advantage? Do know about Abstract Factory?

1937


Can we inherit a class with private constructor?

576


What modifiers may be used with an inner class that is a member of an outer class in java programming?

535


What is meant by oops concept in java?

508


Why do we use variables?

515


what do you mean by classloader in java?

572


What is an image buffer?

539


Is special character in java?

616