Search code examples
javafinal

Blank final variables are used to create immutable objects


I know that blank variables are used to create immutable objects in java i.e. 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);

   }     
 }

Solution

  • 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 (i.e. b.a = ...).