Get / Set methods are there to protect my class fields.
But since Java is working with reference my private fields are still getting exposed..
eg
private Date d;
Date getDate(){
return d;
}
void setDate(Date inD){
//Checks for inD
d = inD;
}
//Still the issue is
getDate().setHours(xyz);
What is the correct approach? Because i dont want to change my Date without using setDate.
Because i dont want to change my Date without using setDate.
Then you shouldn't return a reference to a mutable object in your get
method. For example:
private Date d;
Date getDate() {
// Return a reference to an independent copy of the original data
return new Date(d.getTime());
}
void setDate(Date inD) {
// Checks for inD
d = inD;
}
A better approach (IMO) would be to use immutable types for your fields - the Joda Time API is a much cleaner date/time library and it has plenty of immutable types.
Now that was just an example of course - in other cases you might want to return an immutable view on a mutable object (which you would usually avoid mutating yourself) in order to avoid having to copy a lot of data on each get
call.
There is a good approach for that which is called Defensive Copy,
Date getDate(){
return new Date(d.getTime());
}
you'll get a copy of it and original one will have no affect
Date is just an abomination since it is mutable. What you could do to make it safe, is to return a copy of the date. If that is modified, the original value is not changed.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.