How to make class immutable

Answers were Sorted based on User's Feedback



How to make class immutable..

Answer / a kumar

Make the class as final..
like
public final class String

Is This Answer Correct ?    7 Yes 2 No

How to make class immutable..

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

How to make class immutable..

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

How to make class immutable..

Answer / ganesh reddy

declare calss as a final...

Is This Answer Correct ?    2 Yes 1 No

How to make class immutable..

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

How to make class immutable..

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

Post New Answer

More Core Java Interview Questions

can rmi and corba based applications interact ?

0 Answers  


Define packages in java?

0 Answers  


What do you mean by object?

0 Answers  


Do we have pointers in java?

0 Answers  


What is the vector class in java programming?

0 Answers  






How does abstract modifier work?

1 Answers   Wipro,


We are seeing so many videos/audios as many web sited. But question is these videos or audios are stored in Databases ( Oracle, Mysql, Sybase,... ) or stored any file directory from there they will give the link for that? Pls explain and give sample code to achieve this one? Thanks, Seenu.

0 Answers   Symphony,


Why array is used in java?

0 Answers  


How will you communicate between two applets?

0 Answers  


What are the characteristics provided in jdk1.6 apart from other versions?

3 Answers   TCS,


What is final method in java?

0 Answers  


What is a ternary operator in java?

0 Answers  


Categories