Immutable Classes are those who’s object once created it can’t be change (or value can’t change). So to create Immutable Class in java there are some simple that are listed below.
import java.util.Date
public final class ImmutableSample{
private final int intField; // Is value type
private final String stringField;// Is Immutable
private final Date dateField;// Is mutable
private ImmutableSample(int intField, String stringField, Date dateField){
this.intField = intField;
this.stringField = stringField;
this.dateField = new Date(dateField.getTime());
}
public static ImmutableSample getInstance(int intField, String stringField, Date dateField){
return new ImmutableSample(fld1, fld2, date);
}
//Provide no setter methods
/**
* int is value type variable, So the value in intField going change every
* */
public int getIntField() {
return intField;
}
/**
* String class is also immutable so we can return the instance variable as it is
* */
public String getStringField() {
return stringField;
}
/**
* As Date field is mutable so we create a copy of dateField. So that modification will not effect dateField.
* */
public Date getDateField() {
return new Date(dateField.getTime());
}
@Override
public String toString() {
return intField +" - "+ stringField +" - "+ dateField;
}
}
Please do comment and suggest
Share :
Subscribe to this blog via RSS.
Java 14
Python 2
Ops 3
Shared 3
Angular 1
Web 1
Java (14) Python (2) Wordpress (1) Ops (3) Angular (1) Web (1)