Search code examples
javainterfaceconstantsfinalstatic-block

Why we can't assign a variable inside a static block in INTERFACE ? OCA


I have read that constant values defined in an interface are implicitly public, static, and final.If it so then why can't we assign a value of it inside a interface in static blocks. Where in we can do the same thing in classes inside static blocks.

Interface Example:[Throws Error]

interface Test{
   int x;
   static{
     x=20;
   }    
}

Class Example:[Works Fine]

class Test{
  public static final int x;
  static{
     x=20;
  } 
}

Please tell me the reason of this behavior? If you find this question as duplicate please mark it so I will check.


Solution

  • From JLS Sec 9.3.1:

    Every declarator in a field declaration of an interface must have a variable initializer, or a compile-time error occurs.

    An initializer is simply required by the spec.