How to Make a class Immutable?

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;

}

}

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 134,890评论 18 139
  • 1. Java基础部分 基础部分的顺序:基本语法,类相关的语法,内部类的语法,继承相关的语法,异常的语法,线程的语...
    子非鱼_t_阅读 31,760评论 18 399
  • 背景 一年多以前我在知乎上答了有关LeetCode的问题, 分享了一些自己做题目的经验。 张土汪:刷leetcod...
    土汪阅读 12,769评论 0 33
  • 一. Java基础部分.................................................
    wy_sure阅读 3,834评论 0 11
  • 同学少年思境纯,相逢初遇心自真。 山泉涓涓长流水,长江曲曲九弯春。
    老槐树阅读 113评论 0 2