jQuery in Action, 3rd edition
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
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "static init block in interfaces" Watch "static init block in interfaces" New topic

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

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.

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

Joined: Mar 05, 2008
Posts: 3028
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
I agree. Here's the link: http://aspose.com/file-tools
subject: static init block in interfaces
It's not a secret anymore!