不可变类(Immutable class)是指当创建了这个类的实例以后,就不允许修改它的值了,也就是说,一个对象一旦被创建出来后,在其正规生命周期中,他的成员变量就不能被修改。有点类似于常量,就是只允许其他程序进行读操作,而不允许其他程序对其进行修改操作。
在Java类库中,所有基本类型的包装类都是不可变类,比如:Integer,Long,Float等,除此之外,String类也是不可变的
public class Test {
String str = new String("good");
char[] ch = { 'a', 'b', 'c' };
public static void main(String args[]) {
Test ex = new Test();
ex.change(ex.str, ex.ch);
System.out.print(ex.str + " and ");
System.out.print(ex.ch);
}
public void change(String str, char ch[]) {
str = "test ok";
ch[0] = 'g';
}
}
运行结果:
good and gbc