What is the problem with the below immutable class? Though I say
immutable it is still possible to change the state of an object of this
class. How?
public final Class StoreDate{
private Date storeDate;
StoreDate(Date date){
storeDate = date;
}
public Date getDate(){
return new Date(storeDate.toString())
}
}
1 comment(s) to... “question 10”
1 comments:
Excluding the syntax, no null checks,
below is the solution….
public static void main(String[] args){
Date d = new Date();
StoreDate storeDate = new StoreDate(d);
d.setTime((long)1111111); //Modifies the internal state of the
object..
}
Solution:
public final Class StoreDate{
private Date storeDate;
StoreDate(Date date){
storeDate = new Date(date.toString());
}
public Date getDate(){
return new Date(storeDate.toString())
}
}
Now the internal state can never be changed, as references of date
within object can not be accessed outside.
Post a Comment