PDA

Click to See Complete Forum and Search --> : Public Enum??


rjlohan
Jun 11th, 2002, 03:38 AM
Is there any way to declare a public enum in Java, that can be accessed by at least 2 classes without duplicating the code??

crptcblade
Jun 11th, 2002, 06:49 AM
Unfortunately, enums are nonexistant in Java. The best you can do is use static final variables.


class MyEnums
{
public static final int MOVE_FIRST = 0
public static final int MOVE_PREVIOUS = 1
public static final int MOVE_NEXT = 2
public static final int MOVE_LAST = 3
}


:)

rjlohan
Jun 11th, 2002, 06:22 PM
Yep, ta. I understand that, but how do I make that available to 2 separate classes? Should the enum class be its own compiled class, or should I just duplicate it as an internal class of each of the other 2?

crptcblade
Jun 11th, 2002, 06:31 PM
Well, from a maintenance stand point, it would seem better to compile it as a separate class or interface. Then any changes made later will just flow down to the other classes that use it.

:)

rjlohan
Jun 11th, 2002, 06:43 PM
Ok, so to access the constants, I would need to instantiate the class in any class I want to use it in?
And can I use that class as a parameter to restrict inputs, like an enum in VB, or is it all just for show really?

crptcblade
Jun 11th, 2002, 06:51 PM
Well, if the variables are static, then you just need to reference them by class name. ie,

public class Test
{
public static void main(String[] args)
{
System.out.println(RJsEnumClass.SOME_ENUM_VALUE);
}
}


And have your enum class :

public class RJsEnumClass
{
public static int SOME_ENUM_VALUE = 0;
//blah, blah, blah...
}


And I think you'll have to restrict the input ranges from within the method you are calling.

:)