美文网首页
How to Make a class Immutable?

How to Make a class Immutable?

作者: Arthur_6c78 | 来源:发表于2017-09-12 17:26 被阅读0次

    Don’t provide “setter” methods or methods that modify fields or objects referred to by fields.

    Make all fieldsfinalandprivate.

    Prevent overriding

    The best way to prevent overriding is declaring your class as afinal class.

    Factory method instance creation and Private Constructor

    Never pass the reference of the Mutable objects

    Let put all these and create the immutable class.

    public final class ImmutableClassExample

    {

    //Both String and Integer is Immutable

    private final String val1;

    private final Integer val2;

    //Date is a Mutable field

    private final Date date1;

    public ImmutableClassExample(String val1,Integer val2,Date date1)

    {

    this.val1=val1;

    this.val2=val2;

    this.date1=new Date(date1.getTime());

    }

    public String getVal1()

    {

    return val1;

    }

    public Integer getVal2()

    {

    return val2;

    }

    public Date getDate()

    {

    return new Date(date1.getTime());

    }

    public static ImmutableClassExample getImmutableClassExampleObject(String a,Integer b,Date c)

    {

    return new ImmutableClassExample(a,b,c);

    }

    public String toString()

    {

    return val1+" --- "+val2+" --- "+date1;

    }

    }

    相关文章

      网友评论

          本文标题:How to Make a class Immutable?

          本文链接:https://www.haomeiwen.com/subject/amacsxtx.html