dghtr
dghtr

Reputation: 581

Regarding immutable class

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());


    }
}

Upvotes: 0

Views: 97

Answers (2)

Abhinav Maheshwari
Abhinav Maheshwari

Reputation: 192

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

Upvotes: 0

Luchian Grigore
Luchian Grigore

Reputation: 258688

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.

Upvotes: 4

Related Questions