How to make class immutable
Answers were Sorted based on User's Feedback
Answer / a kumar
Make the class as final..
like
public final class String
| Is This Answer Correct ? | 7 Yes | 2 No |
Answer / kanchan
1. Don't provide any methods that modify the object
2. Ensure that no methods may be overridden. This prevents
careless or malicious subclasses from compromising the
immutable behavior of the class. Preventing
method overrides is generally done by making the class final
3. Make all fields final.
4. Make all fields private. This prevents clients from
modifying fields directly.
| Is This Answer Correct ? | 3 Yes | 0 No |
Answer / vijayakumar chinnasamy
Steps:
1. Create class as final class
2. Make all the properties i.e instance variable as final.
3. Avoid or make the least access for the setter method
for properties.
| Is This Answer Correct ? | 2 Yes | 0 No |
Answer / al rahid
1. Declare the Class as final (this inherently makes all
member function final)
2. Declare member variables private (not necessarily final,
because private instance variable are accessed via public
member functions only, e.g. in java.lang.String class,
variable "hash" is declared as "private int hash;" with no
final keyword).
| Is This Answer Correct ? | 2 Yes | 1 No |
Answer / atul
If declare class as final that means can not Inherited
in subclass.if declare final data members then must be
initializing at randomly or inside constructor otherwise
generate error
| Is This Answer Correct ? | 0 Yes | 0 No |
What is meant by vector class, dictionary class, hash table class, and property class?
Explain the difference between the Boolean & operator and the && operator?
Can you declare the main method as final?
Can we sort list in java?
How many types of threads are there in java?
What is an iterator java?
where u use Abstraction and Interface in real time
Is java a super set of javascript?
What is the best way to findout the time/memory consuming process?
why the primitive data type have classes?
why applet doesn't have main? isn't possible a program with out main?
What does it mean that a method or field is “static”?