Java中的不可变类更改值导致问题

时间:2018-09-02 16:26:13

标签: java

// An immutable class
public final class Student {
    final String name;
    final int regNo;

    public Student(String name, int regNo) {
        this.name = name;
        this.regNo = regNo;
    }
    public String getName() {
        return name;
    }
    public int getRegNo() {
        return regNo;
    }
}

class Test {
    public static void main(String args[]) {
        Student s = new Student("ABC", 101);
        System.out.println(s.name);
        System.out.println(s.regNo);


        // Case 1 :: s.regNo = 102; It will throw exception because we can't change the final value
        // Case 2 ::

        String s = "test"; // String immutable class so as per above class if I try to change the value of s then it should also causing issue or throw exception
        But it will not throw any exception.

        String s = "test1"; // It will not throw any exception but in case 1 it will throw exception        

    }
}

需要了解Case1和Case2。请帮忙。

  

我的问题是String是不可变的类。因此,如果我们更改了   字符串值,那么它将创建其他对象,但是如果我们创建自己的对象   不变的类,那么一旦我们无法更改值   根据最终变量分配值。

2 个答案:

答案 0 :(得分:0)

String是一个不可变的类,意味着无法[*]更改给定字符串对象的值。分配s1 = "test"时,就是将不同对象分配给同一变量。这类似于进行s = new Student("new name", 123)

当然,您也可以将s定义为final以防止对其进行重新分配,但这与s的类型是不可变的事实无关。

[*]至少以“适当”的方式进行,而不求助于反射,字节码操作和其他“不熟练”的技术

答案 1 :(得分:0)

在情况2中,您的字符串变量 s 不是最终的,因此您可以为其分配一个不同的值。 如果像final String s = "test";

那样,将遇到与情况1相同的错误。
相关问题