wood burning stoves 2.0*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes static init block in interfaces Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Murach's Java Servlets and JSP this week in the Servlets forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "static init block in interfaces" Watch "static init block in interfaces" New topic
Author

static init block in interfaces

pradeepta chopra
Ranch Hand

Joined: Jul 05, 2008
Posts: 137
we can declare a static final constant in an interface.
Why cant we put a static init block in a interface since it also has only one copy and is constant too
Ashish Hareet
Ranch Hand

Joined: Jul 14, 2001
Posts: 375
Pradeepta,

Consider the following



Although the above example assigns the value to someVar, there is no way for the compiler to know that variable someVar is definitely assigned. Besides that, it also violates the other rule where members variables of an interface are implicitly public, static & final.

HTH
Ashish Hareet
[ August 03, 2008: Message edited by: Ashish Hareet ]
Mike Simmons
Ranch Hand

Joined: Mar 05, 2008
Posts: 2987
    
    9
Well, that's not really true. Consider this class:

All I did was change "interface" to "class", and add "public final static" (which was all true implicitly for an interface, but must be stated explicitly for a class). Now the code compiles with no problems. The compiler can be sure that someVar is definitely assigned - it just looks at all static initializers, to make sure that the variable gets assigned. Much like it would look at the contents of constructors if we were talking about a final instance field (though there are some differences).

Pradeepta: some might tell you that interfaces are not supposed to contain any implementation details, and a static initializer is an implementation detail. This is sort of true, but there are other ways to put implementation details inside interfaces (in variable initializers and in nested classes).

I think the real answer here is that the Java language designers were just inconsistent on this point. They sort of didn't want implementation details, but they didn't completely block them. Oh well. For better or worse, that's the way they set up the language, and I think it's unlikely to change now. I mean, some change is possible, but it's generally a lot of work convincing enough people to support a particular change. And this particular issue doesn't really seem to bother anyone.
pradeepta chopra
Ranch Hand

Joined: Jul 05, 2008
Posts: 137
thanks all
 
jQuery in Action, 2nd edition
 
subject: static init block in interfaces
 
Similar Threads
implicit and explicit casting
Static Init Block Problem
Execution Order of Static, Init, Instance Blocks
How is a compile-time constant static vaiable causing initialization???
Static