How to make a class immutable?

Answers were Sorted based on User's Feedback



How to make a class immutable?..

Answer / vaibhav

1 Make the all variables of class final and private
2. Make only private constructor

Is This Answer Correct ?    5 Yes 7 No

How to make a class immutable?..

Answer / java

1.Make the class as final
2.Make the data members as private
3.write the public getter methods

Ex:
public class ClassImmutable {


public static void main(String[] args) {
ImmutableTest it=new ImmutableTest(10,"Count");
System.out.println(it.getString());
System.out.println(it.getValue());

}

}

final class ImmutableTest{
private int i;
private String str;
public ImmutableTest(int i,String str){
this.i=i;
this.str=str;

}
public int getValue(){
return i;
}

public String getString(){
return str;
}
}

Is This Answer Correct ?    0 Yes 2 No

How to make a class immutable?..

Answer / raju

Just Make the class as a final

Is This Answer Correct ?    29 Yes 41 No

How to make a class immutable?..

Answer / teja

dont provider setters and provide the parameter constructor

Is This Answer Correct ?    10 Yes 27 No

How to make a class immutable?..

Answer / rahul

create a class , having some private variables and setter
method for that variable , In constructor pass the
arguments to set this variable.

Is This Answer Correct ?    7 Yes 33 No

Post New Answer

More Core Java Interview Questions

what is type of statement in jdbc connection?

3 Answers  


What are parameters in a method?

0 Answers  


What is return code?

0 Answers  


Which method cannot be overridden in java?

0 Answers  


What is meant by call by reference?

0 Answers  






how to create a jar file in java

1 Answers  


Does java support multi dimensional arrays ?

6 Answers  


5 Coding best practices you learned in java?

0 Answers  


Can we have static methods in an interface?

0 Answers  


Is it possible to create Userdefined Unchecked Exception also?If Yes, give an example?

2 Answers   ADP,


Difference between stack and queue?

0 Answers   Flextronics,


What language is pass by reference?

0 Answers  


Categories