Win a copy of The Little Book of Impediments (e-book only) this week in the Agile and Other Processes forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

A question about constants

 
Kamil Hlubek
Ranch Hand
Posts: 49
2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi everyone,

In the OCAJP 7 Summary by Bagdoury Mohammed Amine ( yes, again ) is written :

An interface’s variables are implicitly public, final & static. They should be assigned at declaration. It’s methods are implicitly public and they can’t be final or static.


My question is now, how you can assign a public final static variable in another statement, because there is written "should be assigned" and not have to, but everytime I ever tried to assign such a variable in different statements I got a compiler error.
It would be also nice if somebody could write me in which extract you can read all the stuff with the constants ( that means, when you have to initialize a constant and when not etc. ) in the JLS.

 
Roel De Nijs
Sheriff
Posts: 10662
144
AngularJS Chrome Eclipse IDE Hibernate Java jQuery MySQL Database Spring Tomcat Server
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Kamil Hlubek wrote:My question is now, how you can assign a public final static variable in another statement, because there is written "should be assigned" and not have to, but everytime I ever tried to assign such a variable in different statements I got a compiler error.

That's almost correct! "should" has to be "must" (as you already discovered yourself). Because you can't use a static initializer block in an interface (like you can with a class). This won't compileSo you have to write something like thisBut you could of course initialize this variable using a method from a classThis code uses an instance method, but it would work as well if calculateAbc() would have been a class method.

Kamil Hlubek wrote:It would be also nice if somebody could write me in which extract you can read all the stuff with the constants ( that means, when you have to initialize a constant and when not etc. ) in the JLS.

It's not from the JLS, but I think it's even better (*): this post has a great and understandable explanation about the initialization of class, instance, and local variables (even when they are marked final).

Hope it helps!
Kind regards,
Roel

(*) I wrote that post so probably I'm a little biased
 
nick woodward
Ranch Hand
Posts: 370
11
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
That link is excellent, regardless of the author ;)
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic