How to make a class immutable?
Answers were Sorted based on User's Feedback
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 |
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 |
Answer / teja
dont provider setters and provide the parameter constructor
| Is This Answer Correct ? | 10 Yes | 27 No |
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 |
Is 0 a real number?
Which class is extended by all other classes?
What is the difference between compiler and jvm?
What are the differences between this and super keyword?
What do you mean by an interface in java?
Explain yield() method in thread class ?
What is quick sort in java?
What is meant by anonymous class?
How much ram can a 64 bit processor theoretically?
Is assembly language a low level language?
How do you remove duplicates in java?
Why should we create an object? what is a need of it? Apart from access members of a class i want what is a need of object what does it contain?? In normal class to access any member of thaht class we create object where as for static class we access its members using class name. what is a difference between them... thanks in advance.