Java Mutable and Immutable Objects

摘要: This article shows you the difference between Mutable and Immutable objects in Java

This article shows you the difference between Mutable and Immutable objects in Java

1. Mutable object – You can change the states and fields after the object is created. For examples: StringBuilder, java.util.Date and etc.

2. Immutable object – You cannot change anything after the object is created. For examples: String, boxed primitive objects like Integer, Long and etc.

1. Java Mutable Example

Normally, it provides a method to modify the field value, and the object can be extended.

MutableExample.java
package com.mkyong;
public class MutableExample {
	private String name;
	MutableClass(String name) {
		this.name = name;
	public String getName() {
		return name;
	// this setter can modify the name
	public void setName(String name) {
		this.name = name;
	public static void main(String[] args) {
		MutableExample obj = new MutableExample("mkyong");
		System.out.println(obj.getName());
		// update the name, this object is mutable
		obj.setName("new mkyong");
		System.out.println(obj.getName());

Output

mkyong
new mkyong

2. Java Immutable Example

To create an Immutable object, make the class final, and don’t provide any methods to modify the fields.

ImmutableExample.java
package com.mkyong;
// make this class final, no one can extend this class
public final class ImmutableExample {
	private String name;
	ImmutableExample (String name) {
		this.name = name;
	public String getName() {
		return name;
	//no setter
	public static void main(String[] args) {
		ImmutableExample obj = new ImmutableExample("mkyong");
		System.out.println(obj.getName());
		// there is no way to update the name after the object is created.
		// obj.setName("new mkyong");
		// System.out.println(obj.getName());

Output

mkyong
Note
Immutable object is simple, thread-safe (no need synchronization), less prone to error and more secure. If possible, make all objects immutable.

P.S Please refer to the Effective Java Book – Item 15: Minimize mutability.

References

  1. Mutable vs immutable objects
  2. Immutable objects as per java docs

上一篇: Debian Show apt-get package version
下一篇: Gradle How to continue build if test is failed
 评论 ( What Do You Think )
名称
邮箱
网址
评论
验证
   
 

 


  • 微信公众号

  • 我的微信

站点声明:

1、一号门博客CMS,由Python, MySQL, Nginx, Wsgi 强力驱动

2、部分文章或者资源来源于互联网, 有时候很难判断是否侵权, 若有侵权, 请联系邮箱:summer@yihaomen.com, 同时欢迎大家注册用户,主动发布无版权争议的 文章/资源.

3、鄂ICP备14001754号-3, 鄂公网安备 42280202422812号