File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Beginning Java and the fly likes ConstantInterface vs ConstantClass(Enum) Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "ConstantInterface vs ConstantClass(Enum)" Watch "ConstantInterface vs ConstantClass(Enum)" New topic

ConstantInterface vs ConstantClass(Enum)

Seetharaman Venkatasamy
Ranch Hand

Joined: Jan 28, 2008
Posts: 5575

I know there are many recommendation for Constant class. but some time it is convenient to declare constant in interface. for example say,

I have a specification like below:

there may be x, y, ..z client who may create extra return like ERROR -1 blah, blah(they may create extra constant class)..... but some may required exactly either ON or OFF. why i should allow this client to create one more file for constant. I could have create one more constant file in my API and serve o client but why the extra file? and client have to read the file also..

what you guys say?
dennis deems
Ranch Hand

Joined: Mar 12, 2011
Posts: 808
I say constants do not belong in an interface. And surely this example is better served by an enum?
Winston Gutkowski

Joined: Mar 17, 2011
Posts: 8942

Dennis Deems wrote:I say constants do not belong in an interface.



Bats fly at night, 'cause they aren't we. And if we tried, we'd hit a tree -- Ogden Nash (or should've been).
Articles by Winston can be found here
Rob Spoor

Joined: Oct 27, 2005
Posts: 20273

Thirded. I really prefer classes like java.sql.Types over interfaces like javax.swing.SwingConstants. Just look at the many classes that implement the latter

How To Ask Questions How To Answer Questions
Campbell Ritchie

Joined: Oct 13, 2005
Posts: 46362
It used to be thought it was a good idea to have constants in interfaces, but that caused problems when a class implemented that interface. Those constants became part of the public interface of all those classes. More recent thinking has it that those constants can be put in a class and imported into any classes needing them. You will find a bit more here, including a reference to Joshua Bloch’s book.
I agree. Here's the link:
subject: ConstantInterface vs ConstantClass(Enum)
It's not a secret anymore!