edgards
edgards

Reputation: 99

How to Make a Class Mutable in Java

I just found a tutorial, the tutorial described how to make a class immutable

The question is, variable of Integer type in the tryModification() method is already immutable, do you think this class represents immutability?

import java.util.Date;

public final class ImmutableClass {

private final Integer immutableField1;

private final String immutableField2;

private final Date mutableField;

//default private constructor will ensure no unplanned construction of
//the class
private ImmutableClass(Integer fld1, String fld2, Date date){

    this.immutableField1 = fld1;
    this.immutableField2 = fld2;
    this.mutableField = new Date(date.getTime());




}

//Factor method to store object creation logic in single place
public static ImmutableClass createNewInstance(Integer fld1, String fld2, 
        Date date){

    return new ImmutableClass(fld1, fld2, date);


}

public Integer getImmutableField1(){

    return immutableField1;
}

public String getImmutableField2(){
    return immutableField2;
}

//Date class is mutable so we need little care here
//we should not return the reference of original instance variable
//Instead, a new date object, with content copied to it, should be returned 

public Date getMutableField(){

    return new Date(mutableField.getTime());
}

public String toString(){

    return immutableField1 + " " + immutableField2 + " " + mutableField;



}

}

import java.util.Date;

public class TestMain {

public static void main(String args[]){





    ImmutableClass im = 
            ImmutableClass.createNewInstance(100, "test", new Date());

    System.out.println(im);

    tryModification(im.getImmutableField1(), im.getImmutableField2(), im.getMutableField());
    System.out.println(im);

    System.out.println(test);



}

private static void tryModification(Integer fld1, String fld2, 
        Date mutableField){

    fld1 = 304;
    fld2 = "Test Changed";
    mutableField.setDate(10);




}

}

Upvotes: 1

Views: 1671

Answers (1)

Paul Boddington
Paul Boddington

Reputation: 37645

Yes, it's an immutable class. You've done all the right things - the class is final, all the fields are final, you've made a copy of the mutable object passed to the constructor (the Date), and your getMutableField method returns a copy too.

The reason why the line

tryModification(im.getImmutableField1(), im.getImmutableField2(), im.getMutableField());

does not mutate the instance of your class is that im.getMutableField() returns a copy of the Date instance in the ImmutableClass instance.

Upvotes: 1

Related Questions