为什么我仍然可以对这个最终变量进行更改? [英] Why can I still make changes to this final variable?

查看:150
本文介绍了为什么我仍然可以对这个最终变量进行更改?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果 name 被声明为 final ,为什么我仍然可以调用 name.append ,输出为: shreya ?我认为一旦分配了值就无法更改最终变量?

If name is declared final, why i can still call name.append and the output is: shreya? I thought final variables cannot be changed once a value is assigned?

public class Test1 {

    final static StringBuilder name = new StringBuilder("sh");
    public static void main(String[] args) {

        name.append("reya");
        System.out.println(name);
    }

}


推荐答案

final 指的是无法更改引用,例如你不能说 name = new StringBuilder()使引用的对象不可变。

final refers to not being able to change the reference, e.g. you cannot say name = new StringBuilder(). It does not make the referenced object immutable.

Immutability是的属性。可变类型的对象总是可变的。

Immutability is a property of a class. An object of a mutable type is always mutable.

这篇关于为什么我仍然可以对这个最终变量进行更改?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆