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 do u mean by wrapper Class? What do u mean by Jvm... How do u change JVM for other OS? Or No need to Change ...? its like tricky

6 Answers   Accenture, EDS,


what is servlet enginee?

0 Answers   Covansys,


how a programmer confirms that the data submitted has been succesfully inserted into the database(either oracle or my sql).. How a programmer confirm if there is any problem with the program he wrote for insertion

2 Answers   SAP Labs,


Can a list be null in java?

0 Answers  


What are access modifiers?

1 Answers   Infosys,






Is multiple inheritance supported by java?

0 Answers  


What is externalizable?

0 Answers  


Can you make a constructor final?

0 Answers  


What is meant by data hiding in java?

0 Answers   Aspire, Infogain,


how can i kill thread without stop() and destroy()

1 Answers  


An inner class can actually be a subclass of the outer class? a. true b. false

2 Answers  


What is arrays fill in java?

0 Answers  


Categories