How to make a class immutable?

Answer Posted / 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



Post New Answer       View All Answers


Please Help Members By Posting Answers For Below Questions

What is a variable simple definition?

576


Why stringbuffer is faster than string?

533


What are the four corner stones of oop?

542


Is empty .java file name a valid source file name?

583


How do you implement polymorphism in our day to day life?

2760






What is binary search in java?

553


How can an object be unreferenced?

538


What is the use of singleton class?

519


What is jagged array in java?

527


Can a static block throw exception?

651


What is entry set in java?

529


How to reverse string in java?

613


how to run ecllipse with jettyserver for windows environment using batch file

1490


Tell me the latest versions in java related areas?

578


Explain how to force the garbage collection in java.

529