简体   繁体   English

空白的最终变量用于创建不可变对象

[英]Blank final variables are used to create immutable objects

I know that blank variables are used to create immutable objects in java ie Objects whose member can't be changed How does the following lines of code work without any problem 我知道空白变量用于在java中创建不可变对象,即其成员无法更改的对象以下代码行如何正常工作而没有任何问题

import java.util.*;

class B
{
    int a;
}    
public class BlankFinal
{
   public static void main(String args[])
   {
      final B b;
      b=new B();
      b.a=1;

      System.out.println(b.a);

      b.a=23;         // b object's a member is changed even though b is 
                      // blank final 

      System.out.println(b.a);

   }     
 }

The fact that b is final only prevents you from assigning a new value to b (after its initial initialization). b是final的事实只会阻止您为b分配新值(在初始初始化之后)。 It doesn't prevent you from calling methods of B that mutate the state of the object referenced by b , or mutating the instance variables of the object referenced by b directly (ie ba = ... ). 它不会阻止你调用的方法B是由变异引用的对象的状态b ,或突变被引用的对象的实例变量b直接(即ba = ... )。

The reference to B b is final, and cannot be changed. B b的引用是最终的,不能更改。 When you try to change the value of the datafield ba , it will allow you to do so because it does not change that reference. 当您尝试更改数据字段ba的值时,它将允许您这样做,因为它不会更改该引用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM