Why Java wouldn't allow initialisation of static final variable (e.g. static final int d) in constructor? -


this question has answer here:

i experimenting initialisation of different type of variables in java. can initialise final variable (e.g. final int b) , static variable (e.g. static int c) in constructor can't initialise static final variable (e.g. static final int d) in constructor. ide display error message.

why might java not allow initialisation of static final variable in constructor?

public class initialisingfields {     int a;     final int b;     static int c;     static final int d;      initialisingfields(){         = 1;         b = 2;         c = 3;         d = 4;     }      public static void main(string[] args) {         initialisingfields = new initialisingfields();      }  } 

error message:

exception in thread "main" java.lang.runtimeexception: uncompilable source code - cannot assign value final variable d     @ jto.initialisingfields.<init>(initialisingfields.java:22)     @ jto.initialisingfields.main(initialisingfields.java:26) java result: 1 

a static variable shared instances of class, each time create instance of class, same variable assigned again. since final, can assigned once. therefore not allowed.

static final variables should guaranteed assigned once. therefore can assigned either in same expression in declared, or in static initializer block, executed once.


Comments