How can I modify the body of the code (this can include the body of the constructor) to protect Person instances against alteration: Once a Person is created, it should not be possible to modify it.
It may seem like overkill but the addition of final to each of the private field declarations will make your intent to have immutable fields clearer. As you and Carey have already noted, if you want to keep your fields immutable, your getter methods should return defensive copies of any fields that are mutable objects rather than the references themselves.
Another reason for not Using Date: look in the Java™ Tutorials and see what else is on offer. I think you will go for a nice pound of LocalDate, which is immutable. If you have mutable reference tyes as fields (and remember that arrays are implicitly mutable) always take a defensive copy of any instances passed into your object or returned out of it.
There is another bit missing for immutability: that class isn't declared as final. There's more about immutability in the Java™ Tutorials.
Technically the class still can't guarantee immutability, because its getters can be overridden by a sub-class. Either make the class or its methods final.
You should make the class final, otherwise it is possible for a subclass to add a field and restore mutability. Making class final implicitly makes all its methods behave as final methods.
Campbell Ritchie wrote:You should make the class final, otherwise it is possible for a subclass to add a field and restore mutability.
I don't consider that to break immutability. Sure, the new properties and methods of the class may be mutable, but any code that uses references of the immutable supertype won't notice any difference at all.
I challenge you to implement MutablePerson in such a way that the program's view of immutable is altered in any way.
Stephan van Hulst wrote:. . . any code that uses references of the immutable supertype won't notice any difference at all. . . .
That might be a reference to the immutable supertype but the runtime type is mutable; you might need a cast to make Billy Bunter go to a different school, but it can be done.
Yes, it is bad design to add fields like that, and it will mess up equals() too, but it can be done.
Immutability is a deceptively simple concept. Many programmers out there, even good ones, can fall victim to any of a number of pitfalls so don't feel too bad, Campbell.
Post by:autobot
It's a tiny ad only because the water is so cold.
a bit of art, as a gift, the permaculture playing cards