java - Initialize a static final field in the constructor -


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

i can't see why prohibited. keywords interfere each other?

a constructor called each time instance of class created. thus, above code means value of x re-initialized each time instance created. because variable declared final (and static), can this

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

but, if remove static, allowed this:

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

or this:

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

Comments

Popular posts from this blog

Javascript line number mapping -

c# - Is it possible to remove an existing registration from Autofac container builder? -

php - Mysql PK and FK char(36) vs int(10) -