We help IT Professionals succeed at work.

'Global' variables defined in interfaces

harvk asked
Medium Priority
Last Modified: 2010-03-31
If I have the need of some 'global' variables/markers, I can declare some public static final int's or whatever. But if I have larger needs, I can make the classes implement an interface with those declarations.

My question is, in an interface, variables should be
public static final OR just
public final ?
Is there a difference (when declared in an interface)?

Watch Question

Analyst Programmer
No difference, since all the variables (more precisely, "constants") defined in an interface is implicitly "public", "static" and "final".
But think about what you're doing.....  

The only reason your using an interface so you can avoid prefixing the constants with their class/interface name.  

Think about this - are you using interfaces in the way they were intended?

Furthermore, if I was to receive your code to maintain and i see a reference in your class to INCOME_TAX_RATE.  Where would I find where it was declared?  

1. All the interfaces implemented by your class
2. All the superclasses of your class
3. All the interfaces implemented by superclasses of your class.

This is prety nasty.  Would it not be easier provide one or more constant classes or interfaces and refer to the contstants as CLASSNAME.CONSTANT_NAME

just a thought...



Thanks pkwan.

Skin, I appreciate your comment, but pkwan got there first. However, I don't fully agree with your arguments on interface use; I find some 'C' logic there.
If you were to maintain my code, you'd definately get the whole package rather than a single source file. CLASS.NAME naming is better usually, but not always, especially if you are working with packages.

Thanks anyway for your thoughts.

Explore More ContentExplore courses, solutions, and other research materials related to this topic.