Win a copy of Functional Reactive Programming this week in the Other Languages forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

How to define constants for several classes?

 
Allen Williams
Ranch Hand
Posts: 136
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
How do you implement what in C++ would correspond to a header file where constants for use by several classes could be defined? For example, server request codes?

C++ equivalent example:


TIA
 
Bear Bibeault
Author and ninkuma
Marshal
Pie
Posts: 65229
95
IntelliJ IDE Java jQuery Mac Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
enum
 
Srinivas Kalvala
Ranch Hand
Posts: 257
Firefox Browser Hibernate Linux
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hello,

possible options are:
----------

enum,
constant file ( almost like what you want),

with keys,
--------
property file.
 
Jim Yingst
Wanderer
Sheriff
Posts: 18671
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
If you're using JDK 5 or later, then yes enums are probably your best option. If you're stuck with JDK 1.4 or earlier, you might want to check out this article. Note that it was written before JDK 5 came out, and when it refers to "enum" it means "enum" as used in C/C++, not the newer Java enum.

It's also possible to do something like this:

In general you're better off with either an enum or the typesafe enumeration from the article. But you may find older code that uses public static final ints (or other types), as above.
 
Rahul Bhattacharjee
Ranch Hand
Posts: 2308
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Create a interface with all the constant values in that.This would be the header equivalent in Java and as you import the header in C programs , in java you can implement that interface where you want to use those constants.

Or, you can have a public constant class having all such constant value as static values.Now you can access those using the classname.variablename
 
Pratibha Malhotra
Ranch Hand
Posts: 199
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

Create a interface with all the constant values in that.This would be the header equivalent in Java and as you import the header in C programs , in java you can implement that interface where you want to use those constants.

Or, you can have a public constant class having all such constant value as static values.Now you can access those using the classname.variablename


Using Java 1.5's static-import feature, you can import static members (attributes, methods, classes) of an interface/class.



Using static import enables userto use static members without specifying the class/Interface name.

In above examples context
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic