1

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.

Gaurav Pathak
  • 2,576
  • 1
  • 10
  • 20

4 Answers4

2

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.

Andy Turner
  • 137,514
  • 11
  • 162
  • 243
2

The Java Language Specification indeed only allows a variable initializer.

This probably was a deliberate design decision. Interfaces were introduced and classes were restricted to single inheritance, as in C++ multiple inheritance created murky waters; resolved now in C++, but not very readable in code, and of quite limited usefulness.

In a static initializer one could do all sort of things, like System.out.println and for loops. They probably did want slim interfaces. Certainly not normal initializers { } (= multiple inheritance in a way: order of evaluating a constructor). Maybe someone can tell whether class loading with static initializers in interfaces poses overhead.

Joop Eggen
  • 107,315
  • 7
  • 83
  • 138
1

There is no initializer for interface. So you can't initialize using static or instance block. You can use abstract class for these scenarios.

Vaisakh PS
  • 1,181
  • 2
  • 10
  • 19
-2

In general Interfaces are used to define which functions a certain class should have by implementing it. So i'm not sure assigning values inside a Interface is the way to go.

class Test implements yourInterface {
   @Override
   function myInterfaceFunction() {
     // code goes here
   }
}

Maybe you could explain what it is you're trying to achieve and why you need the Interface.

PieterJan
  • 105
  • 1
  • 10