Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

How to declare global constants accesable by multiple classes ?

Status
Not open for further replies.

sergeiY

Programmer
Feb 13, 2003
132
AU
I need to have a global constants accessable from multiple classes within a (default) package. How can I declare them so all classes can see them ? I was told to create an interface but I am not quite sure how it will work.

Thank you
 
Create a generic class such as GlobalConstants.class and just create static variables for the variables you want to have global access. If they don't change make them final. Becareful maybe to make them private and create getter and setter methods...i am showing the lazy way.

public class GlobalConstants{

public static String name = "Chilly Billy";
public static String address = "10 Chicken head Lane";

}

 
Another way is to create an interface like this:
Code:
public interface GlobalConstants
{
   static String name = "Chilly Billy";
   static String address = "10 Chicken head Lane";
}
Any class that needs to use them only has to implement the interface:
Code:
public class foo implements GlobalConstants
{
   public foo()
   {
      System.err.println(name);
   }
}
 
I really like the interface approach...i guess it depends on if you need to update the global variables, then you may need a class.

 
If you use a class, you can also include static methods that are used globally.

I tend to use an interface to hold static final variables, and a class to hold static global methods. As I get better, though, I use fewer and fewer global methods.
 
Thank you guys. Interface is the way to go for me.

Thanks a lot.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top