This week's book giveaway is in the OCMJEA forum. We're giving away four copies of OCM Java EE 6 Enterprise Architect Exam Guide and have Paul Allen & Joseph Bambara on-line! See this thread for details.
In one of my recent projects, I used an interface to declare constants like public static final int UNKNOWN_ERROR = 100. I have several such constants declared in interface and what ever class wants to use these constants can implement the interface. However, my lead was not happy with the approach, instead he suggested me to declare constants in a separate class with a private constructor and refer the constants using classname.constant approach, and gave me an explanation on the benefits of having this approach, relative to compile time vs run time, which I really did not understand.
I did not dare back to ask him on this, but am certainly curious on this approach. Can some body shed some light on the benefits of declaring the constants in interface vs declaring them in a class. Which is better over the other and why?
While declaring them in a class is certainly much better than in an interface, don't declare them in a separate class just for this purpose either. Declare constants in an existing context where they make sense.
Joined: Dec 17, 2010
Paul Clapham wrote:I was going to write an answer but then I found that the Wikipedia article Constant interface said everything I was going to say, better, and it said more.
Thanks for pointing me to the resource. Could you please elaborate on "Contrary to the compile-time tactical utility of implementing a constants interface, the incidental run-time artifacts have little practical purpose (cf. marker interfaces which also have no methods but are useful at run-time)."
Are the Marker interfaces a compile-time interfaces and the Constant Interfaces a run time? Is this what it means?
Rajani Gummadi wrote:Are the Marker interfaces a compile-time interfaces and the Constant Interfaces a run time? Is this what it means?
No, there's no such thing as compile-time and run-time interfaces. But then what you wrote there isn't what the article said, so there's no point in asking what your statement means. Here's the important bit of what the article said:
Wikipedia wrote:marker interfaces which also have no methods but are useful at run-time