简体   繁体   中英

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

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). 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 = ... ).

The reference to B b is final, and cannot be changed. 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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