0

I have developed a below code based on the concept of immutability , as we know in java string class is immutable so I also developed the below class as immutable , please advise me is it correct as per the immutablility..

 public final class BrokenPerson { private String firstName; private String lastName; private Date dob; public BrokenPerson( String firstName, String lastName, Date adob) { this.firstName = firstName; this.lastName = lastName; this.dob = new Date(adob.getTime()); } public String getFirstName() { return this.firstName; } public String getLastName() { return this.lastName; } public Date getDOB() { return new Date(dob.getTime()); } } 

2 Answers 2

4

final applied to a class makes it non-extendable, not immutable.

You want your members to be final.

public final class BrokenPerson { private final String firstName; private final String lastName; private final Date dob; //... } 

Of course, as it is now, the class can't be modified because the private fields aren't modified by any member methods, but, for strictness, you should mark them as final.

Sign up to request clarification or add additional context in comments.

2 Comments

@Luchian..yeah buddy make it final give more shield
There's also certain guarantees made of final fields in the Java Memory Model when referencing instances across multiple threads.
0

This is correct, as there is no way to modify the object

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.