Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Initialize a static final field in the constructor

public class A  {         private static final int x;      public A()      {         x = 5;     } } 
  • final means the variable can only be assigned once (in the constructor).
  • static means it's a class instance.

I can't see why this is prohibited. Where do those keywords interfere with each other?

like image 643
Yaron Levi Avatar asked Feb 23 '11 16:02

Yaron Levi


People also ask

Can final static be initialized in constructor?

If you declare a static variable in a class, if you haven't initialized it, just like with instance variables compiler initializes these with default values in the default constructor. Yes, you can also initialize these values using the constructor.

How do you initialize a static variable in a constructor?

The only way to initialize static final variables other than the declaration statement is Static block. A static block is a block of code with a static keyword. In general, these are used to initialize the static members. JVM executes static blocks before the main method at the time of class loading.

Can final field be set in constructor?

In Java, non-static final variables can be assigned a value either in constructor or with the declaration. But, static final variables cannot be assigned value in constructor; they must be assigned a value with their declaration.


2 Answers

A constructor will be called each time an instance of the class is created. Thus, the above code means that the value of x will be re-initialized each time an instance is created. But because the variable is declared final (and static), you can only do this

class A {         private static final int x;      static {         x = 5;     } } 

But, if you remove static, you are allowed to do this:

class A {         private final int x;      public A() {         x = 5;     } } 

OR this:

class A {         private final int x;      {         x = 5;     } } 
like image 53
adarshr Avatar answered Sep 18 '22 16:09

adarshr


static final variables are initialized when the class is loaded. The constructor may be called much later, or not at all. Also, the constructor will be called multiple times (with each new object ), so the field could no longer be final.

If you need custom logic to initialize your static final field, put that in a static block

like image 41
Sean Patrick Floyd Avatar answered Sep 19 '22 16:09

Sean Patrick Floyd