It's not a secret anymore!
The moose likes Beginning Java and the fly likes Constants Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of Java Interview Guide this week in the Jobs Discussion forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Constants" Watch "Constants" New topic


Abhijith Prabhakar
Ranch Hand

Joined: Dec 29, 2006
Posts: 56
I want to declare a file which contains all the constants of my project. Could you guys tell me shall i declare all the constants in a Class or an Interface? and Why?
Svend Rost
Ranch Hand

Joined: Oct 23, 2002
Posts: 904

Given the information you provide: that depends on your problem.

/Svend Rost
Anupam Sinha
Ranch Hand

Joined: Apr 13, 2003
Posts: 1090
I would suggest that you use a class. The class can be package private when you don't want the constants to be seen outside the package. The constant interface pattern (usage of interfaces for just declaring constants) should be avoided.
Stan James
(instanceof Sidekick)
Ranch Hand

Joined: Jan 29, 2003
Posts: 8791
I'd resist doing all of the constants for a system in one place. You'll make it hard to reuse any subset of your system without dragging that whole constants class along.

You can usually find them a home along with the classes that really need them. For example, if you have a set of constants for log message severity they probably belong on the Logger class or in the logger package.

Also look into Enums. In Java 5 and later they can replace some constants like those severity levels in nifty ways.
[ March 07, 2007: Message edited by: Stan James ]

A good question is never answered. It is not a bolt to be tightened into place but a seed to be planted and to bear more seed toward the hope of greening the landscape of the idea. John Ciardi
I agree. Here's the link:
subject: Constants
It's not a secret anymore!